import { Injectable, UnauthorizedException } from "@nestjs/common";
import type { CanActivate, ExecutionContext } from "@nestjs/common";
import type { Request } from "express";
import { AuthLoginService } from "@bff/modules/auth/application/auth-login.service.js";
import { ErrorCode } from "@customer-portal/domain/common";

@Injectable()
export class LocalAuthGuard implements CanActivate {
  constructor(private readonly loginService: AuthLoginService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<Request>();
    const body = (request.body ?? {}) as Record<string, unknown>;

    const email = typeof body["email"] === "string" ? body["email"] : "";
    const password = typeof body["password"] === "string" ? body["password"] : "";

    if (!email || !password) {
      throw new UnauthorizedException({
        message: "Invalid credentials",
        code: ErrorCode.INVALID_CREDENTIALS,
      });
    }

    const user = await this.loginService.validateUser(email, password, request);
    if (!user) {
      throw new UnauthorizedException({
        message: "Invalid credentials",
        code: ErrorCode.INVALID_CREDENTIALS,
      });
    }

    // Attach user to request (replaces Passport's req.user behavior)
    (request as Request & { user: unknown }).user = user;

    return true;
  }
}
