import { Test } from '@nestjs/testing';
import { AuthService } from '@models/users/services/auth.service';
import { SignIn } from '@models/users/useCases/SignIn/SignIn';
import { fakerFR } from '@faker-js/faker';
import { RegisterDTO, SignInDTO } from 'app-types';
import { PrismaService } from '@/database/services/prisma.service';
import { UserRepo } from '@models/users/repos/user.repo';
import { JwtService } from '@nestjs/jwt';
import { Register } from '@models/users/useCases/Register/Register';
import { jwtConstants } from '@models/users/constants';

describe('SignIn Controller', () => {
  let controller: SignIn;
  let register: Register;
  let authService: AuthService;
  let userRepo: UserRepo;
  let jwtService: JwtService;

  beforeEach(async () => {
    jwtService = new JwtService({
      secret: jwtConstants.secret,
    });
    userRepo = new UserRepo(new PrismaService());
    authService = new AuthService(userRepo, jwtService);

    const module = await Test.createTestingModule({
      controllers: [SignIn, Register],
      providers: [
        {
          provide: AuthService,
          useFactory: () => new AuthService(userRepo, jwtService),
        },
        {
          provide: UserRepo,
          useValue: userRepo,
        },
        {
          provide: JwtService,
          useValue: jwtService,
        },
      ],
    }).compile();

    register = module.get(Register);
    controller = module.get(SignIn);
    authService = module.get(AuthService);
  });

  describe('signIn', () => {
    it('should sign in user successfully', async () => {
      const mockUser: RegisterDTO = {
        email: fakerFR.internet.email(),
        password: 'password123',
        firstname: fakerFR.person.firstName(),
        lastname: fakerFR.person.lastName(),
      };

      await register.execute(mockUser);

      const mockRequest: SignInDTO = {
        email: mockUser.email,
        password: 'password123',
      };

      const result = await controller.signIn(mockRequest);

      expect(result.access_token).toBeDefined();
    });

    it('should pass through errors from auth service', async () => {
      try {
        await controller.signIn({
          email: fakerFR.internet.email(),
          password: 'nimporte quoi',
        });
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
      }
    });
  });
});
