import { Injectable, UnauthorizedException } from "@nestjs/common";
import type { CanActivate, ExecutionContext } from "@nestjs/common";
import type { Request } from "express";
import { AuthOrchestrator } from "@bff/modules/auth/application/auth-orchestrator.service.js";

@Injectable()
export class LocalAuthGuard implements CanActivate {
  constructor(private readonly authOrchestrator: AuthOrchestrator) {}

  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("Invalid credentials");
    }

    const user = await this.authOrchestrator.validateUser(email, password, request);
    if (!user) {
      throw new UnauthorizedException("Invalid credentials");
    }

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

    return true;
  }
}
