import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import type { Request } from 'express';
import { UserService, type PublicUser } from '../../user/user.service';
import type { JwtPayload } from '../types/jwt-payload';

// access 토큰 검증 전략 — access_token 쿠키에서 토큰 추출
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(
    config: ConfigService,
    private readonly userService: UserService,
  ) {
    super({
      // 쿠키(access_token)에서 JWT 추출
      jwtFromRequest: (req: Request): string | null =>
        (req?.cookies as Record<string, string> | undefined)?.access_token ??
        null,
      ignoreExpiration: false,
      secretOrKey: config.getOrThrow<string>('JWT_ACCESS_SECRET'),
    });
  }

  // 토큰 유효 시 실제 사용자 존재를 재확인하고 공개 형태로 반환 → req.user
  async validate(payload: JwtPayload): Promise<PublicUser> {
    const user = await this.userService.findById(payload.sub);
    if (!user) {
      throw new UnauthorizedException();
    }
    return UserService.toPublic(user);
  }
}
