export type MailPayload = {
    driver: string | null;
    host: string | null;
    port: number | null;
    username: string | null;
    has_password: boolean;
    encryption: string | null;
    from_address: string | null;
    from_name: string | null;
    effective_from_address: string | null;
    effective_from_name: string | null;
};

export type SettingsPayload = {
    site_name: string;
    site_support_email: string | null;
    site_terms_url: string | null;
    site_privacy_url: string | null;
    signup_disabled: boolean;
    require_email_verification: boolean;
    require_signup_consent: boolean;
    allow_data_export: boolean;
    allow_self_delete: boolean;
    kit_author_emails: string;
    default_currency: string;
    mail: MailPayload;
    // Phase 6 — populated by AppServiceProvider::applyAppSettings overlay.
    // Optional so older payloads still parse cleanly during the rollout.
    app_debug?: boolean;
    app_cache_enabled?: boolean;
    session_driver?: 'database' | 'file';
    audit_retention_days?: number;
    notifications?: {
        // Customer-facing
        subscription_activated_enabled: boolean;
        subscription_canceled_enabled: boolean;
        plan_changed_enabled: boolean;
        renewal_reminder_enabled: boolean;
        refund_issued_enabled: boolean;
        payment_action_required_enabled: boolean;
        subscription_paused_enabled: boolean;
        subscription_halted_enabled: boolean;
        subscription_expired_enabled: boolean;
        user_welcome_enabled: boolean;
        renewal_reminder_days: number;
        // Admin-facing
        admin_new_subscription_enabled: boolean;
        admin_subscription_canceled_enabled: boolean;
        admin_refund_issued_enabled: boolean;
        admin_payment_failed_enabled: boolean;
        admin_webhook_failed_enabled: boolean;
        admin_user_registered_enabled: boolean;
        admin_email: string;
    };
    notification_templates?: Array<{
        key: string;
        label: string;
        audience: 'customer' | 'admin';
    }>;
    email_template?: {
        logo: string | null;
        logo_url: string | null;
        logo_width: number;
        alignment: 'left' | 'center' | 'right';
        /** Raw override value — empty string = inherit from Appearance. */
        font_family: string;
        /** Resolved font name after applying the Appearance fallback —
         *  used as a hint in the editor when no override is set. */
        resolved_font_family: string;
        footer_text: string;
        font_options: string[];
    };
    /** Google OAuth credentials (Social login tab). Secret never echoed. */
    google?: {
        client_id: string | null;
        has_client_secret: boolean;
        google_enabled: boolean;
        button_active: boolean;
    };
    /** GitHub OAuth credentials (Social login tab). Secret never echoed. */
    github?: {
        client_id: string | null;
        has_client_secret: boolean;
        github_enabled: boolean;
        button_active: boolean;
    };
    /** AI generation settings (AI tab). Key never echoed. */
    ai?: {
        ai_enabled: boolean;
        ai_model: string | null;
        ai_timeout: number;
        has_api_key: boolean;
        key_active: boolean;
        host: {
            max_execution_time: number;
            can_extend_time: boolean;
        };
    };
    /** Read-only Envato license snapshot (License tab). Purchase code masked. */
    license?: {
        licensed: boolean;
        status: string | null;
        purchase_code_masked: string | null;
        buyer_email: string | null;
        supported_until: string | null;
        purchased_on: string | null;
        type: string | null;
        domain: string | null;
        last_verified_at: string | null;
        item_id: string;
    };
    /** Local-only update state (Updates tab). Live check fetched separately. */
    update?: {
        current_version: string;
        supported_until: string | null;
        support_active: boolean;
        licensed: boolean;
        product_url: string;
    };
};

/** Live "Check for updates" response from /admin/settings/update/check. */
export type UpdateCheck = {
    current_version: string;
    latest_version: string | null;
    available: boolean;
    archive: string | null;
    description: string | null;
    release_date: string | null;
    support_active: boolean;
    can_one_click: boolean;
    checked: boolean;
};

export type FormShape = {
    site_name: string;
    site_support_email: string;
    site_terms_url: string;
    site_privacy_url: string;
    signup_disabled: boolean;
    require_email_verification: boolean;
    require_signup_consent: boolean;
    allow_data_export: boolean;
    allow_self_delete: boolean;
    kit_author_emails: string;
    default_currency: string;
    mail_driver: string;
    mail_host: string;
    mail_port: string;
    mail_username: string;
    mail_password: string;
    mail_encryption: string;
    mail_from_address: string;
    mail_from_name: string;
    app_debug: boolean;
    app_cache_enabled: boolean;
    session_driver: 'database' | 'file';
    audit_retention_days: string;
};

export type FormErrors = Partial<Record<keyof FormShape, string>>;

export type UpdateFn = <K extends keyof FormShape>(
    key: K,
    value: FormShape[K],
) => void;

export function toForm(s: SettingsPayload): FormShape {
    return {
        site_name: s.site_name ?? '',
        site_support_email: s.site_support_email ?? '',
        site_terms_url: s.site_terms_url ?? '',
        site_privacy_url: s.site_privacy_url ?? '',
        signup_disabled: Boolean(s.signup_disabled),
        require_email_verification: Boolean(s.require_email_verification),
        require_signup_consent: Boolean(s.require_signup_consent),
        allow_data_export: Boolean(s.allow_data_export ?? true),
        allow_self_delete: Boolean(s.allow_self_delete ?? true),
        kit_author_emails: s.kit_author_emails ?? '',
        default_currency: s.default_currency ?? 'USD',
        mail_driver: s.mail?.driver ?? 'smtp',
        mail_host: s.mail?.host ?? '',
        mail_port:
            s.mail?.port === null || s.mail?.port === undefined
                ? ''
                : String(s.mail.port),
        mail_username: s.mail?.username ?? '',
        mail_password: '',
        mail_encryption: s.mail?.encryption ?? '',
        mail_from_address: s.mail?.from_address ?? '',
        mail_from_name: s.mail?.from_name ?? '',
        app_debug: s.app_debug ?? false,
        app_cache_enabled: s.app_cache_enabled ?? true,
        session_driver: s.session_driver ?? 'database',
        audit_retention_days: String(s.audit_retention_days ?? 730),
    };
}

export function csrfHeaders(): Record<string, string> {
    const xsrf = document
        .querySelector('meta[name="csrf-token"]')
        ?.getAttribute('content');
    const cookieMatch = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]+)/);
    const cookieToken = cookieMatch ? decodeURIComponent(cookieMatch[1]) : null;
    const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
    };
    if (xsrf) headers['X-CSRF-TOKEN'] = xsrf;
    if (cookieToken) headers['X-XSRF-TOKEN'] = cookieToken;
    return headers;
}
