import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { UserService } from '../user/user.service';
import { SafeUser } from '../user/dto/user-safe.dto';
import { UserRole } from '../user/user-role.enum';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private configService: ConfigService,
    private userService: UserService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('JWT_SECRET')!,
    });
  }

  // Passport first verifies the JWT's signature and expiration, then calls this method.
  async validate(payload: {
    sub: string;
    username: string;
    role?: string;
    tenantId?: string;
  }): Promise<SafeUser | null> {
    const user = await this.userService.findOneByUsername(payload.username);
    if (user) {
      const { password, ...result } = user;

      // In a multi-tenant setup, the tenantId in the payload is the "default" or "last active" one.
      // But it can be overridden by the x-tenant-id header in the guard.
      // Map the backend isAdmin flag to the global UserRole
      const computedRole = result.isAdmin ? UserRole.SUPER_ADMIN : UserRole.USER;

      return {
        ...result,
        role: payload.role || computedRole,
        tenantId: payload.tenantId || result.tenantId
      } as SafeUser;
    }
    return null;
  }
}
