import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../../prisma/prisma.service';
import { JwtPayload } from './jwt-payload.interface';
import { RequestTenantContext } from '../tenancy/tenant-query.helper';
import { UserStatus } from '@prisma/client';
import { getJwtSecret } from './jwt-secret';

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

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.extractToken(request);

    if (!token) {
      throw new UnauthorizedException('Authentication required');
    }

    try {
      const payload = await this.jwtService.verifyAsync<JwtPayload>(token, {
        secret: getJwtSecret(),
      });

      // Verify user still exists and is ACTIVE
      const user = await this.prisma.user.findUnique({
        where: { id: payload.sub },
        include: {
          organization: true,
          customRole: {
            include: {
              permissions: true,
            },
          },
        },
      });

      if (!user) {
        throw new UnauthorizedException('User no longer exists');
      }

      // Password reset or suspension bumps sessionVersion, revoking older tokens.
      if (payload.sv !== user.sessionVersion) {
        throw new UnauthorizedException('Session has been revoked');
      }

      if (user.status !== UserStatus.ACTIVE) {
        throw new UnauthorizedException('User account is not active');
      }

      // If user belongs to an organization, verify organization is not SUSPENDED
      if (user.organization && user.organization.status === 'SUSPENDED') {
        throw new UnauthorizedException('Organization access is suspended');
      }

      // Strip sensitive password hash before attaching to request
      const { passwordHash: _passwordHash, resetTokenHash: _resetTokenHash, invitationTokenHash: _invitationTokenHash, ...safeUser } = user;

      request.user = safeUser;
      request.tenantContext = {
        userId: user.id,
        role: user.role,
        tenantId: user.tenantId,
      } as RequestTenantContext;

      return true;
    } catch (err) {
      if (err instanceof UnauthorizedException) {
        throw err;
      }
      throw new UnauthorizedException('Invalid or expired token');
    }
  }

  private extractToken(request: any): string | null {
    const authHeader = request.headers?.authorization;
    if (authHeader && authHeader.startsWith('Bearer ')) {
      return authHeader.substring(7);
    }
    if (request.cookies) {
      if (request.cookies['__Host-tcx_token']) {
        return request.cookies['__Host-tcx_token'];
      }
      if (request.cookies['tcx_token']) {
        return request.cookies['tcx_token'];
      }
    }
    return null;
  }
}
