/**
 * login-user.use-case.ts
 * LoginUserUseCase: lógica para iniciar sesión.
 * - Valida datos
 * - Busca el usuario por email
 * - Compara las contraseñas
 * - Genera el JWT
 */

import { LoginUserDto, LoginUserDtoValidator } from "../../dtos/index.js";
import { AuthRepository } from "../../repositories/auth.repository.js";
import { CustomError } from "../../errors/custom.error.js";
import { BcryptAdapter } from "../../../config/bcrypt.js";
import { JwtAdapter } from "../../../config/jwt.js";

export interface LoginUserResponse {
  user: {
    id: number;
    email: string;
    name: string;
  };
  token: string;
}

export class LoginUserUseCase {
  constructor(private repository: AuthRepository) {}

  async execute(data: unknown): Promise<LoginUserResponse> {
    // Validar DTO
    const dto = LoginUserDtoValidator.validate(data);

    // Buscar usuario por email
    const user = await this.repository.findByEmail(dto.email);
    if (!user) {
      throw CustomError.unauthorized("Invalid credentials");
    }

    // Comparar contraseñas
    const isPasswordValid = await BcryptAdapter.compare(dto.password, user.password);
    if (!isPasswordValid) {
      throw CustomError.unauthorized("Invalid credentials");
    }

    // Generar JWT
    const token = JwtAdapter.generate({
      id: user.id,
      email: user.email,
    });

    return {
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
      },
      token,
    };
  }
}