'use client';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { cmsApi } from '../../lib/api.js';
export const EMAIL_PROVIDER_OPTIONS = [
    { value: 'resend', label: 'Resend' },
    { value: 'smtpcom', label: 'SMTP.com' },
    { value: 'ses', label: 'Amazon SES' },
    { value: 'smtp', label: 'SMTP server' },
];
const EMPTY_FORM = {
    provider: '',
    from: '',
    apiKey: '',
    channel: '',
    region: '',
    host: '',
    port: '',
    secure: false,
    smtpUser: '',
    smtpPass: '',
};
function toForm(s) {
    return {
        provider: s.provider ?? '',
        from: s.from ?? '',
        apiKey: '',
        channel: s.channel ?? '',
        region: s.region ?? '',
        host: s.host ?? '',
        port: s.port != null ? String(s.port) : '',
        secure: s.secure ?? false,
        smtpUser: s.smtpUser ?? '',
        smtpPass: '',
    };
}
function snapshot(f) {
    return JSON.stringify(f);
}
export function useEmailSettings(canEdit) {
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState(null);
    const [form, setForm] = useState(EMPTY_FORM);
    const [meta, setMeta] = useState({
        envProvider: null,
        factoryAvailable: false,
        envSenderActive: false,
        platformAdapter: false,
    });
    const [storedSecrets, setStoredSecrets] = useState({
        provider: null,
        hasApiKey: false,
        apiKeyLast4: undefined,
        hasSmtpPass: false,
    });
    const [lastTest, setLastTest] = useState({});
    const [saveState, setSaveState] = useState('idle');
    const [saveError, setSaveError] = useState(null);
    const [testing, setTesting] = useState(false);
    const [testResult, setTestResult] = useState(null);
    const baselineRef = useRef(snapshot(EMPTY_FORM));
    const applyResponse = useCallback((d) => {
        const nextForm = toForm(d.settings);
        setForm(nextForm);
        baselineRef.current = snapshot(nextForm);
        setMeta({
            envProvider: d.envProvider,
            factoryAvailable: d.factoryAvailable,
            envSenderActive: d.envSenderActive,
            platformAdapter: d.platformAdapter,
        });
        setStoredSecrets({
            provider: d.settings.provider,
            hasApiKey: d.settings.hasApiKey,
            apiKeyLast4: d.settings.apiKeyLast4,
            hasSmtpPass: d.settings.hasSmtpPass,
        });
        setLastTest({
            status: d.settings.lastTestStatus,
            testedAt: d.settings.lastTestedAt,
            error: d.settings.lastTestError,
        });
    }, []);
    const load = useCallback(async () => {
        setLoading(true);
        setLoadError(null);
        const res = await cmsApi('/email/settings');
        if (res.error || !res.data) {
            setLoadError(res.error ?? 'Failed to load email settings');
            setLoading(false);
            return;
        }
        applyResponse(res.data);
        setSaveState('idle');
        setLoading(false);
    }, [applyResponse]);
    useEffect(() => {
        void load();
    }, [load]);
    const setField = useCallback((key, value) => {
        setForm((prev) => ({ ...prev, [key]: value }));
        setSaveState('idle');
        setSaveError(null);
        setTestResult(null);
    }, []);
    const dirty = useMemo(() => snapshot(form) !== baselineRef.current, [form]);
    const save = useCallback(async () => {
        if (!canEdit)
            return;
        setSaveState('saving');
        setSaveError(null);
        let body;
        if (form.provider === '') {
            body = { provider: null };
        }
        else {
            body = {
                provider: form.provider,
                from: form.from.trim(),
                // Secrets: omit = keep stored value; include only when re-entered.
                ...(form.apiKey.trim() ? { apiKey: form.apiKey.trim() } : {}),
                ...(form.provider === 'smtpcom' && form.channel.trim()
                    ? { channel: form.channel.trim() }
                    : {}),
                ...(form.provider === 'ses' ? { region: form.region.trim() } : {}),
                ...(form.provider === 'smtp'
                    ? {
                        host: form.host.trim(),
                        ...(form.port.trim() ? { port: Number(form.port) } : {}),
                        secure: form.secure,
                        ...(form.smtpUser.trim() ? { smtpUser: form.smtpUser.trim() } : {}),
                        ...(form.smtpPass ? { smtpPass: form.smtpPass } : {}),
                    }
                    : {}),
            };
        }
        const res = await cmsApi('/email/settings', {
            method: 'PUT',
            body: JSON.stringify(body),
        });
        if (res.error || !res.data) {
            setSaveState('error');
            setSaveError(res.error ?? 'Failed to save email settings');
            return;
        }
        const nextForm = toForm(res.data.settings);
        setForm(nextForm);
        baselineRef.current = snapshot(nextForm);
        setStoredSecrets({
            provider: res.data.settings.provider,
            hasApiKey: res.data.settings.hasApiKey,
            apiKeyLast4: res.data.settings.apiKeyLast4,
            hasSmtpPass: res.data.settings.hasSmtpPass,
        });
        setLastTest({});
        setSaveState('success');
    }, [canEdit, form]);
    const sendTest = useCallback(async () => {
        setTesting(true);
        setTestResult(null);
        const res = await cmsApi('/email/settings/test', {
            method: 'POST',
            body: JSON.stringify({}),
        });
        setTesting(false);
        if (res.error || !res.data?.success) {
            const message = res.error ?? 'Test send failed';
            setTestResult({ success: false, message });
            setLastTest({ status: 'failed', testedAt: new Date().toISOString(), error: message });
            return;
        }
        setTestResult({
            success: true,
            message: `Test email sent to ${res.data.sentTo ?? 'your address'}.`,
        });
        setLastTest({ status: 'success', testedAt: new Date().toISOString() });
    }, []);
    const reset = useCallback(() => {
        setForm(JSON.parse(baselineRef.current));
        setSaveState('idle');
        setSaveError(null);
        setTestResult(null);
    }, []);
    return {
        loading,
        loadError,
        form,
        stored: {
            hasApiKey: storedSecrets.hasApiKey,
            apiKeyLast4: storedSecrets.apiKeyLast4,
            hasSmtpPass: storedSecrets.hasSmtpPass,
            sameProvider: form.provider !== '' && form.provider === storedSecrets.provider,
        },
        env: { provider: meta.envProvider, senderActive: meta.envSenderActive },
        factoryAvailable: meta.factoryAvailable,
        platformAdapter: meta.platformAdapter,
        lastTest,
        dirty,
        saveState,
        saveError,
        testing,
        testResult,
        setField,
        save,
        sendTest,
        reset,
        reload: () => void load(),
    };
}
//# sourceMappingURL=useEmailSettings.js.map