import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { Request } from 'express';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
import { CapiException } from '../errors/capi.exception';
import { CAPIErrorCode } from '../errors/capi-error-codes';
import { HttpStatus } from '@nestjs/common';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
    private readonly reflector: Reflector,
    private readonly prisma: PrismaService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) return true;

    const request = context.switchToHttp().getRequest<Request>();

    // Admin and internal routes use their own auth guards
    if (request.path.startsWith('/admin-api') || request.path.startsWith('/internal')) {
      return true;
    }

    const token = this.extractToken(request);

    if (!token) {
      throw new CapiException(CAPIErrorCode.AUTH_UNAUTHORIZED, '请先登录', HttpStatus.UNAUTHORIZED);
    }

    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: this.configService.get<string>('jwt.secret'),
      });

      // Reject admin tokens on user endpoints
      if (payload.type === 'admin') {
        throw new CapiException(CAPIErrorCode.AUTH_WRONG_TOKEN_TYPE, '无效的访问令牌', HttpStatus.UNAUTHORIZED);
      }

      const user = await this.prisma.user.findUnique({
        where: { id: payload.sub },
        select: { id: true, status: true, deletedAt: true, role: true, email: true },
      });

      if (!user || user.deletedAt) {
        throw new CapiException(CAPIErrorCode.AUTH_USER_DELETED, '账号不存在或已注销', HttpStatus.UNAUTHORIZED);
      }

      if (user.status !== 'active') {
        throw new CapiException(CAPIErrorCode.AUTH_USER_DISABLED, '账号已被禁用', HttpStatus.UNAUTHORIZED);
      }

      request.user = { id: user.id, email: user.email, role: user.role };
      return true;
    } catch (err) {
      if (err instanceof CapiException || err instanceof UnauthorizedException) throw err;
      throw new CapiException(CAPIErrorCode.AUTH_UNAUTHORIZED, '登录已过期，请重新登录', HttpStatus.UNAUTHORIZED);
    }
  }

  private extractToken(request: Request): string | undefined {
    const authHeader = request.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) return undefined;
    return authHeader.split(' ')[1];
  }
}
