import { Test } from '@nestjs/testing';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ShareShooting } from '@/models/shootings/useCases/ShareShooting/ShareShooting';
import { ShareCustomerGallery } from '@/models/shootings/useCases/ShareCustomerGallery/ShareCustomerGallery';
import { ShootingRepo } from '@/models/shootings/repos/shooting.repo';
import { CustomerRepo } from '@/models/shootings/repos/customer.repo';
import { EmailSender } from '@/modules/emails/services/email-sender';
import { EmailModule } from '@/modules/emails/modules/email.module';
import { TestEmailsController } from '@/modules/emails/testing/test-emails.controller';
import {
  FakeEmailService,
  SentHtmlEmail,
} from '@/modules/emails/testing/fake-email.service';
import { User } from '@/models/users/domain/user';

const user = {
  id: 'user-1',
  email: 'photographe@studio-m.test',
  firstname: 'Louis',
  lastname: 'Grinwald',
} as User;

const shooting = {
  id: 'shooting-1',
  name: 'Mariage Dupont',
  customer: {
    id: 'customer-1',
    email: 'client@studio-m.test',
    firstname: 'Jean',
    lastname: 'Dupont',
  },
};

describe('Partage par email (EmailSender / FakeEmailService)', () => {
  let fakeEmailService: FakeEmailService;
  let shareShooting: ShareShooting;
  let shareCustomerGallery: ShareCustomerGallery;
  let fetchSpy: jest.SpyInstance;

  beforeEach(async () => {
    fetchSpy = jest
      .spyOn(global, 'fetch')
      .mockRejectedValue(new Error('Appel réseau interdit en test'));

    const moduleRef = await Test.createTestingModule({
      controllers: [ShareShooting, ShareCustomerGallery],
      providers: [
        FakeEmailService,
        { provide: EmailSender, useExisting: FakeEmailService },
        {
          provide: ShootingRepo,
          useValue: { findById: jest.fn().mockResolvedValue(shooting) },
        },
        {
          provide: CustomerRepo,
          useValue: {
            findById: jest.fn().mockResolvedValue(shooting.customer),
          },
        },
        { provide: EventEmitter2, useValue: { emit: jest.fn() } },
      ],
    }).compile();

    fakeEmailService = moduleRef.get(FakeEmailService);
    shareShooting = moduleRef.get(ShareShooting);
    shareCustomerGallery = moduleRef.get(ShareCustomerGallery);
  });

  afterEach(() => {
    fetchSpy.mockRestore();
  });

  it('capture l’email de partage d’un shooting sans appel réseau', async () => {
    const response = await shareShooting.execute(
      shooting.id,
      {
        emails: ['client@studio-m.test', 'invite@studio-m.test'],
        name: 'Jean',
      },
      user,
    );

    expect(response).toEqual({ success: true });
    expect(fetchSpy).not.toHaveBeenCalled();

    const sentEmails = fakeEmailService.getSentEmails() as SentHtmlEmail[];
    expect(sentEmails).toHaveLength(2);
    expect(sentEmails.map((email) => email.to[0].email)).toEqual([
      'client@studio-m.test',
      'invite@studio-m.test',
    ]);
    expect(sentEmails[0].type).toBe('html');
    expect(sentEmails[0].subject).toContain('Mariage Dupont');
    expect(sentEmails[0].htmlContent).toContain('mode=customer');
    expect(sentEmails[1].htmlContent).toContain('mode=guest');
    expect(sentEmails[0].replyTo).toEqual({
      email: user.email,
      name: 'Louis Grinwald',
    });
  });

  it('capture l’email de partage d’une galerie client sans appel réseau', async () => {
    const response = await shareCustomerGallery.execute(
      shooting.customer.id,
      { emails: ['invite@studio-m.test'], name: 'Invité', message: 'Bonjour' },
      user,
    );

    expect(response).toEqual({ success: true });
    expect(fetchSpy).not.toHaveBeenCalled();

    const sentEmails = fakeEmailService.getSentEmails() as SentHtmlEmail[];
    expect(sentEmails).toHaveLength(1);
    expect(sentEmails[0].to).toEqual([
      { email: 'invite@studio-m.test', name: 'Invité' },
    ]);
    expect(sentEmails[0].htmlContent).toContain('Bonjour');
  });

  it('vide les emails capturés', async () => {
    await shareCustomerGallery.execute(
      shooting.customer.id,
      { emails: ['invite@studio-m.test'], name: 'Invité', message: '' },
      user,
    );

    fakeEmailService.clear();

    expect(fakeEmailService.getSentEmails()).toEqual([]);
  });
});

describe('EmailModule en NODE_ENV=test', () => {
  it('résout EmailSender vers FakeEmailService et monte GET /__test__/emails', async () => {
    expect(process.env.NODE_ENV).toBe('test');

    const moduleRef = await Test.createTestingModule({
      imports: [EmailModule],
    })
      .useMocker(() => ({}))
      .compile();

    const emailSender = moduleRef.get(EmailSender);
    expect(emailSender).toBeInstanceOf(FakeEmailService);

    const controller = moduleRef.get(TestEmailsController);
    await emailSender.sendTemplateEmail(
      [{ email: 'destinataire@studio-m.test' }],
      42,
      { nom: 'Mariage Dupont' },
    );

    expect(controller.list()).toEqual({
      emails: [
        expect.objectContaining({
          type: 'template',
          templateId: 42,
          to: [{ email: 'destinataire@studio-m.test' }],
          params: { nom: 'Mariage Dupont' },
        }),
      ],
    });

    expect(controller.clear()).toEqual({ success: true });
    expect(controller.list()).toEqual({ emails: [] });
  });
});
