import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy } from "passport-local";
import type { Request } from "express";
import { AuthFacade } from "@bff/modules/auth/application/auth.facade";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authFacade: AuthFacade) {
    super({ usernameField: "email", passReqToCallback: true });
  }

  async validate(
    req: Request,
    email: string,
    password: string
  ): Promise<{ id: string; email: string; role: string }> {
    const user = await this.authFacade.validateUser(email, password, req);
    if (!user) {
      throw new UnauthorizedException("Invalid credentials");
    }
    return user;
  }
}
