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

interface JwtPayload {
  sub: string;
  email: string;
  roles: { code: any; tenantId: string | null; scopeComplexId: string | null }[];
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(config: ConfigService, private readonly prisma: PrismaService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: config.get<string>('JWT_ACCESS_SECRET')!,
      passReqToCallback: true,
    });
  }

  async validate(req: any, payload: JwtPayload): Promise<AuthenticatedUser> {
    const user = await this.prisma.user.findUnique({ where: { id: payload.sub } });
    if (!user || user.status === 'DISABLED') throw new UnauthorizedException();

    // Active tenant from header (multi-tenant: user picks which tenant to act in)
    const headerTenant = req.headers['x-tenant-id'] as string | undefined;
    const isSuperAdmin = payload.roles.some((r) => r.code === 'SUPERADMIN');

    let tenantId: string | null = null;
    if (headerTenant) {
      const allowed = isSuperAdmin || payload.roles.some((r) => r.tenantId === headerTenant);
      if (!allowed) throw new UnauthorizedException('No access to this tenant');
      tenantId = headerTenant;
    } else if (!isSuperAdmin) {
      const firstTenantRole = payload.roles.find((r) => r.tenantId);
      tenantId = firstTenantRole?.tenantId ?? null;
    }

    return {
      userId: user.id,
      email: user.email,
      roles: payload.roles,
      tenantId,
      isSuperAdmin,
    };
  }
}
