import { Injectable } from '@nestjs/common';
import { appForbidden, appUnauthorized } from '../../shared/common/app-error';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../shared/prisma/prisma.service';
import { JwtPayload } from './auth.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    config: ConfigService,
    private prisma: PrismaService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: config.get('JWT_SECRET', 'dev-secret'),
    });
  }

  async validate(payload: JwtPayload) {
    const user = await this.prisma.user.findUnique({
      where: { id: BigInt(payload.sub) },
      include: {
        adminRole: {
          include: {
            role: {
              include: {
                permissions: {
                  include: { permission: true },
                },
              },
            },
          },
        },
      },
    });
    if (!user) {
      throw appUnauthorized('INVALID_CREDENTIALS');
    }
    if (user.status === 'DISABLED') {
      throw appForbidden('ACCOUNT_DISABLED');
    }
    if (user.status === 'SUSPENDED') {
      throw appForbidden(
        user.userType === 'AGENT' ? 'AGENT_ACCOUNT_SUSPENDED' : 'ACCOUNT_SUSPENDED',
      );
    }
    if (user.status !== 'ACTIVE') {
      throw appForbidden('ACCOUNT_DISABLED');
    }
    const permissions =
      user.adminRole?.role?.permissions?.map((rp) => rp.permission.code) ?? [];
    const roleCode = user.adminRole?.role?.code ?? payload.role;
    return {
      id: user.id,
      username: user.username,
      userType: user.userType,
      parentId: user.parentId,
      agentLevel: user.agentLevel,
      locale: user.locale,
      role: roleCode,
      permissions,
    };
  }
}
