import { describe, it, expect, vi, beforeEach } from 'vitest';
import { sendEmail } from './mailer';
import { config } from '../config';

// Mock getServerAppServices to avoid full app initialization
vi.mock('@/lib/services/create-services.server', () => ({
  getServerAppServices: () => ({
    logger: {
      child: () => ({
        info: vi.fn(),
        error: vi.fn(),
        warn: vi.fn(),
      }),
    },
  }),
}));

// Mock config
vi.mock('../config', () => ({
  config: {
    mail: {
      host: 'smtp.example.com',
      port: 587,
      user: 'user',
      pass: 'pass',
      from: 'from@example.com',
      recipients: ['to@example.com'],
    },
  },
  getConfig: vi.fn(),
}));

describe('mailer', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe('sendEmail', () => {
    it('should throw error if MAIL_HOST is missing', async () => {
      // Temporarily nullify host
      const originalHost = config.mail.host;
      (config.mail as any).host = '';

      const result = await sendEmail({
        subject: 'Test',
        html: '<p>Test</p>',
      });

      expect(result.success).toBe(false);
      expect(result.error).toContain('MAIL_HOST is not configured');

      // Restore host
      (config.mail as any).host = originalHost;
    });

    // In a real environment, we'd mock nodemailer, but for now we focus on the validation logic
    // we added. Full SMTP integration tests are usually out of scope for unit tests.
  });
});
