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

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  private readonly logger = new Logger(JwtStrategy.name);

  constructor(
    configService: ConfigService,
    private prisma: PrismaService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET'),
    });
    this.logger.log('JwtStrategy initialized');
  }

  async validate(payload: any) {
    this.logger.debug('Validating JWT payload:', payload);

    try {
      const user = await this.prisma.user.findUnique({
        where: { id: payload.sub },
        select: {
          id: true,
          email: true,
          name: true,
          isAdmin: true,
        },
      });

      if (!user) {
        this.logger.warn('JWT validation failed: User not found:', { userId: payload.sub });
        throw new UnauthorizedException('User not found');
      }

      this.logger.debug('JWT validation successful:', {
        userId: user.id,
        email: user.email,
        name: user.name,
        isAdmin: user.isAdmin,
      });

      return {
        userId: user.id,
        email: user.email,
        name: user.name,
        isAdmin: user.isAdmin,
      };
    } catch (error) {
      this.logger.error('JWT validation error:', {
        error: error.message,
        stack: error.stack,
      });
      throw new UnauthorizedException('Invalid token');
    }
  }
}
