import { ConfigService } from '@nestjs/config';
import { MailerService } from '@nestjs-modules/mailer';
import { MailService } from './mail.service';

describe('MailService', () => {
  let service: MailService;
  let sendMail: jest.Mock;
  let configGet: jest.Mock;

  beforeEach(() => {
    sendMail = jest.fn().mockResolvedValue(undefined);
    configGet = jest.fn().mockReturnValue('https://app.example.com');

    service = new MailService(
      { sendMail } as unknown as MailerService,
      { get: configGet } as unknown as ConfigService,
    );
  });

  it('sends the activation mail with the confirm-email link', async () => {
    await service.userSignUp({
      to: 'user@example.com',
      data: { hash: 'abc123', firstName: 'Max' },
    });

    expect(sendMail).toHaveBeenCalledTimes(1);
    const call = sendMail.mock.calls[0][0];
    expect(call.to).toBe('user@example.com');
    expect(call.template).toBe('activation');
    expect(call.context.url).toBe(
      'https://app.example.com/confirm-email/abc123',
    );
    expect(call.context.firstName).toBe('Max');
  });

  it('sends the reset-password mail with the password-change link', async () => {
    await service.forgotPassword({
      to: 'user@example.com',
      data: { hash: 'xyz789', firstName: 'Erika' },
    });

    expect(sendMail).toHaveBeenCalledTimes(1);
    const call = sendMail.mock.calls[0][0];
    expect(call.to).toBe('user@example.com');
    expect(call.template).toBe('reset-password');
    expect(call.context.url).toBe(
      'https://app.example.com/password-change/xyz789',
    );
    expect(call.context.firstName).toBe('Erika');
  });

  it('works without a firstName (optional personalization)', async () => {
    await service.userSignUp({
      to: 'user@example.com',
      data: { hash: 'abc123' },
    });

    const call = sendMail.mock.calls[0][0];
    expect(call.context.firstName).toBeUndefined();
  });

  it('sends the cashbox export mail with the PDF attachment', async () => {
    const attachment = Buffer.from('%PDF-1.4 fake');

    await service.cashboxExport(
      {
        to: 'vorstand@example.com, kassier@example.com',
        data: { teamName: 'Team A', from: '2026-08-01', to: '2026-08-31' },
      },
      attachment,
      'kassenbuch_team-a_2026-08-01_2026-08-31.pdf',
    );

    expect(sendMail).toHaveBeenCalledTimes(1);
    const call = sendMail.mock.calls[0][0];
    expect(call.to).toBe('vorstand@example.com, kassier@example.com');
    expect(call.template).toBe('cashbox-export');
    expect(call.context.teamName).toBe('Team A');
    expect(call.context.from).toBe('2026-08-01');
    expect(call.context.to).toBe('2026-08-31');
    expect(call.attachments).toEqual([
      { filename: 'kassenbuch_team-a_2026-08-01_2026-08-31.pdf', content: attachment },
    ]);
  });
});
