import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SafeUser } from '../user/dto/user-safe.dto'; // Import SafeUser
import { I18nService } from '../i18n/i18n.service';
import { UserRole } from '../user/user-role.enum';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(
    private authService: AuthService,
    private i18nService: I18nService,
  ) {
    super({ usernameField: 'username' });
  }

  async validate(username: string, password: string): Promise<SafeUser> {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException(this.i18nService.getMessage('incorrectCredentials'));
    }
    const { password: userPassword, ...result } = user; // Destructure to remove password
    return {
      ...result,
      role: user.isAdmin ? UserRole.SUPER_ADMIN : UserRole.USER
    } as SafeUser;
  }
}
