import { validateEmail, formatEmailContent, sendFormspreeEmail } from '../email';

describe('Email Utilities', () => {
  describe('validateEmail', () => {
    it('validates correct email addresses', () => {
      expect(validateEmail('test@example.com')).toBe(true);
      expect(validateEmail('user.name+tag@example.co.uk')).toBe(true);
    });

    it('rejects invalid email addresses', () => {
      expect(validateEmail('not-an-email')).toBe(false);
      expect(validateEmail('@example.com')).toBe(false);
      expect(validateEmail('test@')).toBe(false);
    });
  });

  describe('formatEmailContent', () => {
    const testData = {
      name: 'John Doe',
      email: 'john@example.com',
      phone: '+1234567890',
      company: 'Test Corp',
      message: 'Test message'
    };

    it('formats contact email correctly', () => {
      const { subject, body } = formatEmailContent(testData, 'contact');
      expect(subject).toBe('Contact from John Doe - Puffin Offset');
      expect(body).toContain('Name: John Doe');
      expect(body).toContain('Email: john@example.com');
    });

    it('formats offset email correctly', () => {
      const { subject, body } = formatEmailContent(testData, 'offset');
      expect(subject).toBe('Offset Request - John Doe');
      expect(body).toContain('Name: John Doe');
      expect(body).toContain('Email: john@example.com');
    });
  });

  describe('sendFormspreeEmail', () => {
    const mockFetch = jest.fn();
    global.fetch = mockFetch;

    beforeEach(() => {
      mockFetch.mockClear();
      mockFetch.mockImplementation(() => Promise.resolve({
        ok: true,
        json: () => Promise.resolve({})
      }));
    });

    const testData = {
      name: 'John Doe',
      email: 'john@example.com',
      phone: '+1234567890',
      company: 'Test Corp',
      message: 'Test message'
    };

    it('sends contact form to correct Formspree endpoint', async () => {
      await sendFormspreeEmail(testData, 'contact');
      expect(mockFetch).toHaveBeenCalledWith(
        'https://formspree.io/f/xkgovnby',
        expect.any(Object)
      );
    });

    it('sends offset form to correct Formspree endpoint', async () => {
      await sendFormspreeEmail(testData, 'offset');
      expect(mockFetch).toHaveBeenCalledWith(
        'https://formspree.io/f/xvgzbory',
        expect.any(Object)
      );
    });

    it('handles API errors correctly', async () => {
      mockFetch.mockImplementationOnce(() => Promise.resolve({
        ok: false,
        json: () => Promise.resolve({ error: 'API Error' })
      }));

      await expect(sendFormspreeEmail(testData, 'contact'))
        .rejects
        .toThrow('API Error');
    });
  });
});