import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from '../services/token.service';

function extractJwtFromCookieOrHeader(req: Request): string | null {
  const cookieToken = req.cookies?.['access_token'] as string | undefined;
  if (cookieToken) return cookieToken;
  return ExtractJwt.fromAuthHeaderAsBearerToken()(req);
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    const jwtSecret = process.env['JWT_SECRET'];
    if (!jwtSecret) {
      throw new Error('JWT_SECRET environment variable is required');
    }

    super({
      jwtFromRequest: extractJwtFromCookieOrHeader,
      ignoreExpiration: false,
      secretOrKey: jwtSecret,
      audience: 'goodgo-api',
      issuer: 'goodgo-platform',
    });
  }

  validate(payload: JwtPayload): JwtPayload {
    return { sub: payload.sub, phone: payload.phone, role: payload.role };
  }
}
