jest.mock('@/lib/network-security/safe-fetch', () => ({
    safeOutboundFetch: jest.fn(),
}));

import { TeamsChannel } from '../teams.channel';
import { safeOutboundFetch } from '@/lib/network-security/safe-fetch';

const fetchMock = safeOutboundFetch as jest.Mock;
const okResponse = () => ({ ok: true, status: 200, text: async () => '' });

describe('TeamsChannel', () => {
    beforeEach(() => fetchMock.mockReset());

    it('refuses without a webhookUrl', async () => {
        const ch = new TeamsChannel();
        await expect(ch.sendOrThrow('hi', {} as never)).rejects.toThrow(/webhookUrl/);
    });

    it('posts a MessageCard with @type and themeColor', async () => {
        fetchMock.mockResolvedValueOnce(okResponse());
        const ch = new TeamsChannel();
        await ch.sendOrThrow('Monitor X is DOWN', {
            webhookUrl: 'https://example.webhook.office.com/webhookb2/xxx',
        } as never);

        const [url, init] = fetchMock.mock.calls[0];
        expect(url).toBe('https://example.webhook.office.com/webhookb2/xxx');
        const body = JSON.parse(init.body);
        expect(body['@type']).toBe('MessageCard');
        expect(body['@context']).toBe('https://schema.org/extensions');
        expect(body.themeColor).toBe('f59e0b');
        expect(body.text).toBe('Monitor X is DOWN');
    });

    it('uses a custom title if provided', async () => {
        fetchMock.mockResolvedValueOnce(okResponse());
        const ch = new TeamsChannel();
        await ch.sendOrThrow('Monitor X is DOWN', {
            webhookUrl: 'https://example.webhook.office.com/x',
            title: 'EA NetOps',
        } as never);
        const body = JSON.parse(fetchMock.mock.calls[0][1].body);
        expect(body.title).toBe('EA NetOps');
    });

    it('throws on non-2xx', async () => {
        fetchMock.mockResolvedValueOnce({ ok: false, status: 410, text: async () => 'gone' });
        const ch = new TeamsChannel();
        await expect(
            ch.sendOrThrow('hi', { webhookUrl: 'https://example.webhook.office.com/x' } as never),
        ).rejects.toThrow(/Teams 410/);
    });
});
