import { type ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { UnauthorizedException } from '@modules/shared';

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
  override handleRequest<T>(err: Error | null, user: T, _info: unknown, _context: ExecutionContext): T {
    // If the strategy threw a DomainException (e.g. our custom UnauthorizedException),
    // re-throw it directly so GlobalExceptionFilter produces the structured error format.
    if (err) {
      throw err;
    }
    if (!user) {
      throw new UnauthorizedException('Số điện thoại hoặc mật khẩu không đúng');
    }
    return user;
  }
}
