/**
 * A newly typed custom API key that hasn't been saved yet.
 *
 * It lives outside the settings form because the key is never sent back to
 * the browser once saved. "Save Changes" on any general page validates and
 * saves it too, as the old settings form did.
 */
import { create } from 'zustand';
import { __ } from '@wordpress/i18n';
import { ajax, errorMessage } from '@/lib/api';
import { useSettingsStore } from '@/store/settings-store';
import type { AjaxResponse, OptionValues } from '@/types';
import type { ModelsData } from './types';

interface ApiKeyDraft {
    draft: string;
    /** "Change" was clicked while a key is saved. */
    editing: boolean;
    error: string;
    success: string;
}

export const useApiKeyDraft = create<ApiKeyDraft>()( () => ( {
    draft: '',
    editing: false,
    error: '',
    success: '',
} ) );

export type SaveFn = ( extra?: OptionValues ) => Promise<boolean>;

/**
 * Saves the general group, validating and including a newly typed key when
 * the key field is in play (custom key on, field shown, not empty).
 */
export async function saveGeneral( save: SaveFn ): Promise<boolean> {
    const data   = useSettingsStore.getState().sections.models?.data as ModelsData | undefined;
    const values = useSettingsStore.getState().values.general ?? {};
    const { draft, editing } = useApiKeyDraft.getState();
    const apiKey = draft.trim();

    const fieldShown = Boolean( values.wtofe_use_custom_api_key ) && ( ! data?.apiKey.hasKey || editing );
    if ( ! data || ! fieldShown || '' === apiKey ) {
        return save();
    }

    useApiKeyDraft.setState( { error: '', success: '' } );

    let response: AjaxResponse | null;
    try {
        response = await ajax( 'wtofe_validate_api_key', { nonce: data.nonces.validateKey, api_key: apiKey } );
    } catch {
        response = null;
    }

    if ( ! response?.success ) {
        useApiKeyDraft.setState( {
            error: errorMessage( response, __( 'Could not verify the API key. Please try again.', 'ai-content-generator-for-woocommerce' ) ),
        } );
        return false;
    }

    const saved = await save( { wtofe_chatgpt_api_key: apiKey } );
    if ( saved ) {
        useApiKeyDraft.setState( { draft: '', editing: false } );
    }
    return saved;
}
