import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

export interface JwtPayload {
  sub: string;
  clubId: string;
  role: string;
  roles: string[];
  iat?: number;
  exp?: number;
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('jwt.secret') || 'change-me-in-production',
    });
  }

  validate(payload: JwtPayload): JwtPayload {
    if (!payload.sub || !payload.clubId || !payload.role) {
      throw new UnauthorizedException('Invalid token payload');
    }

    const role = payload.role.toLowerCase();
    // Backward compat: if old token has no roles[], derive from role
    const roles = Array.isArray(payload.roles) ? payload.roles.map((r) => r.toLowerCase()) : [role];

    return {
      sub: payload.sub,
      clubId: payload.clubId,
      role,
      roles,
    };
  }
}
