import { jsx as _jsx } from "react/jsx-runtime";
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
const EMPTY_RESPONSE = {
    settings: { provider: null, hasApiKey: false, hasSmtpPass: false },
    envProvider: null,
    factoryAvailable: true,
    envSenderActive: false,
    platformAdapter: false,
};
let getResponse = EMPTY_RESPONSE;
let putResponse = null;
let testResponse = {
    data: { success: true, sentTo: 'admin@example.com' },
    status: 200,
};
const cmsApi = vi.fn(async (endpoint, options) => {
    const method = options?.method ?? 'GET';
    if (endpoint === '/email/settings' && method === 'GET') {
        return { data: getResponse, status: 200 };
    }
    if (endpoint === '/email/settings' && method === 'PUT') {
        return putResponse
            ? { data: putResponse, status: 200 }
            : { error: 'unexpected PUT', status: 500 };
    }
    if (endpoint === '/email/settings/test' && method === 'POST') {
        return testResponse;
    }
    return { data: {}, status: 200 };
});
vi.mock('../../lib/api.js', () => ({
    cmsApi: (e, o) => cmsApi(e, o),
    ensureCsrfToken: vi.fn(async () => { }),
}));
const { EmailSettingsTab } = await import('../../views/settings/EmailSettingsTab.js');
function deepClone(v) {
    return JSON.parse(JSON.stringify(v));
}
beforeEach(() => {
    cmsApi.mockClear();
    getResponse = deepClone(EMPTY_RESPONSE);
    putResponse = null;
    testResponse = { data: { success: true, sentTo: 'admin@example.com' }, status: 200 };
});
describe('EmailSettingsTab', () => {
    it('renders the provider picker with the unconfigured state', async () => {
        render(_jsx(EmailSettingsTab, { role: "ADMIN" }));
        expect(await screen.findByRole('radio', { name: 'None' })).toBeTruthy();
        expect(screen.getByRole('radio', { name: 'Resend' })).toBeTruthy();
        expect(screen.getByRole('radio', { name: 'SMTP.com' })).toBeTruthy();
        expect(screen.getByRole('radio', { name: 'Amazon SES' })).toBeTruthy();
        expect(screen.getByRole('radio', { name: 'SMTP server' })).toBeTruthy();
        expect(screen.getByText(/No email provider configured/)).toBeTruthy();
    });
    it('saves an SMTP.com configuration with the entered key (PUT payload contract)', async () => {
        putResponse = {
            settings: {
                provider: 'smtpcom',
                from: 'noreply@example.com',
                channel: 'transactional',
                hasApiKey: true,
                apiKeyLast4: '-key',
                hasSmtpPass: false,
            },
        };
        render(_jsx(EmailSettingsTab, { role: "ADMIN" }));
        fireEvent.click(await screen.findByRole('radio', { name: 'SMTP.com' }));
        fireEvent.change(screen.getByLabelText('Sender address'), {
            target: { value: 'noreply@example.com' },
        });
        fireEvent.change(screen.getByLabelText('API key'), {
            target: { value: 'smtpcom-secret-key' },
        });
        fireEvent.change(screen.getByLabelText('Sender channel'), {
            target: { value: 'transactional' },
        });
        fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
        await waitFor(() => {
            const put = cmsApi.mock.calls.find(([e, o]) => e === '/email/settings' && o?.method === 'PUT');
            expect(put).toBeTruthy();
            expect(JSON.parse(put[1].body)).toEqual({
                provider: 'smtpcom',
                from: 'noreply@example.com',
                apiKey: 'smtpcom-secret-key',
                channel: 'transactional',
            });
        });
        // After save the key input is cleared and the masked hint appears.
        expect(screen.getByLabelText('API key').value).toBe('');
        expect(await screen.findByText(/ends in -key/)).toBeTruthy();
    });
    it('omits the apiKey from the payload when a stored key is kept', async () => {
        getResponse = {
            ...deepClone(EMPTY_RESPONSE),
            settings: {
                provider: 'resend',
                from: 'old@example.com',
                hasApiKey: true,
                apiKeyLast4: 'k3y9',
                hasSmtpPass: false,
            },
        };
        putResponse = {
            settings: {
                provider: 'resend',
                from: 'new@example.com',
                hasApiKey: true,
                apiKeyLast4: 'k3y9',
                hasSmtpPass: false,
            },
        };
        render(_jsx(EmailSettingsTab, { role: "ADMIN" }));
        const from = await screen.findByLabelText('Sender address');
        expect(await screen.findByText(/ends in k3y9/)).toBeTruthy();
        fireEvent.change(from, { target: { value: 'new@example.com' } });
        fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
        await waitFor(() => {
            const put = cmsApi.mock.calls.find(([e, o]) => e === '/email/settings' && o?.method === 'PUT');
            expect(put).toBeTruthy();
            const body = JSON.parse(put[1].body);
            expect(body).toEqual({ provider: 'resend', from: 'new@example.com' });
            expect(body).not.toHaveProperty('apiKey');
        });
    });
    it('sends a test email and shows the result', async () => {
        getResponse = {
            ...deepClone(EMPTY_RESPONSE),
            settings: {
                provider: 'resend',
                from: 'a@b.co',
                hasApiKey: true,
                apiKeyLast4: 'k3y9',
                hasSmtpPass: false,
            },
        };
        render(_jsx(EmailSettingsTab, { role: "ADMIN" }));
        fireEvent.click(await screen.findByRole('button', { name: /Send test email/ }));
        await waitFor(() => expect(cmsApi).toHaveBeenCalledWith('/email/settings/test', expect.objectContaining({ method: 'POST' })));
        expect(await screen.findByText(/Test email sent to admin@example.com/)).toBeTruthy();
    });
    it('surfaces a failed test send', async () => {
        getResponse = {
            ...deepClone(EMPTY_RESPONSE),
            settings: {
                provider: 'resend',
                from: 'a@b.co',
                hasApiKey: true,
                hasSmtpPass: false,
            },
        };
        testResponse = { error: 'SMTP.com API error (401): bad key', status: 502 };
        render(_jsx(EmailSettingsTab, { role: "ADMIN" }));
        fireEvent.click(await screen.findByRole('button', { name: /Send test email/ }));
        expect(await screen.findByText(/SMTP\.com API error \(401\)/)).toBeTruthy();
    });
    it('shows the env-managed notice and disables editing for non-admins', async () => {
        getResponse = {
            ...deepClone(EMPTY_RESPONSE),
            envProvider: 'resend',
            envSenderActive: true,
        };
        render(_jsx(EmailSettingsTab, { role: "EDITOR" }));
        expect(await screen.findByText(/read-only access/)).toBeTruthy();
        expect(screen.getByText(/Environment variables currently configure/)).toBeTruthy();
        expect(screen.getByRole('radio', { name: 'Resend' }).disabled).toBe(true);
    });
    it('warns when the email plugin is missing for a configured provider', async () => {
        getResponse = {
            ...deepClone(EMPTY_RESPONSE),
            factoryAvailable: false,
            settings: {
                provider: 'resend',
                from: 'a@b.co',
                hasApiKey: true,
                hasSmtpPass: false,
            },
        };
        render(_jsx(EmailSettingsTab, { role: "ADMIN" }));
        expect(await screen.findByText(/requires the email plugin/)).toBeTruthy();
    });
});
//# sourceMappingURL=email-settings.render.test.js.map