import { Injectable, UnauthorizedException, ForbiddenException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy, JwtFromRequestFunction } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { ClsService } from 'nestjs-cls';
import type { Request } from 'express';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuthService, JwtPayload } from '../auth.service';
import { COOKIE_ACCESS_NAME } from '../cookie-config';
import { RolePermissionEntity } from '../../entities/role-permission.entity';
import { RedisService } from '../../redis/redis.service';
import {
  CLS_USER_ID,
  CLS_TENANT_ID,
  CLS_USER_ROLE_NAME,
  CLS_USER_ROLE_ID,
  CLS_USER_PERMISSIONS,
  CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES,
  CLS_READ_ONLY,
  CLS_IMPERSONATOR_ID,
} from '../../common/cls/cls.constants';

/**
 * JwtStrategy — validates JWT and stores user_id + permissions in CLS.
 *
 * Per CLAUDE.md:
 * - created_by and updated_by also read from ClsService automatically
 * - User context stored in CLS after JWT validation
 * - Permissions map stored for visibility scoping (common/auth/visibility.ts)
 */
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  private static readonly PERM_CACHE_PREFIX = 'perm:role:';

  constructor(
    configService: ConfigService,
    private readonly authService: AuthService,
    private readonly cls: ClsService,
    private readonly redisService: RedisService,
    @InjectRepository(RolePermissionEntity)
    private readonly rolePermRepo: Repository<RolePermissionEntity>,
  ) {
    // Cookie-first, Bearer-fallback extractor.
    //
    // Transition mode: FE Phase 3 will switch to cookies, but existing
    // sessions still carry a bearer token in localStorage. Read the
    // cookie first so cookie-based clients don't collide with any
    // stale Authorization header from a browser extension.
    const fromCookie: JwtFromRequestFunction = (req: Request) => {
      const cookies = (req as Request & { cookies?: Record<string, string> }).cookies;
      return cookies?.[COOKIE_ACCESS_NAME] || null;
    };
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        fromCookie,
        ExtractJwt.fromAuthHeaderAsBearerToken(),
      ]),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('JWT_SECRET')!,
    });
  }

  async validate(payload: JwtPayload) {
    const user = await this.authService.validateUserFromToken(payload);

    if (!user) {
      throw new UnauthorizedException('Invalid or expired session');
    }

    // SECURITY: Cross-verify JWT tenant_id matches CLS tenant_id (set by TenantMiddleware)
    // Prevents user from Tenant A sending X-Tenant-Id header for Tenant B
    const clsTenantId = this.cls.get<string>(CLS_TENANT_ID);
    if (!clsTenantId) {
      throw new ForbiddenException('Tenant context missing');
    }
    if (clsTenantId !== user.tenant_id) {
      throw new ForbiddenException('Tenant mismatch: your account does not belong to this tenant');
    }

    // Store user_id in CLS for automatic audit trail (created_by, updated_by)
    this.cls.set(CLS_USER_ID, user.id);
    // Store role name for backward compatibility (some code may still read it)
    this.cls.set(CLS_USER_ROLE_NAME, user.role?.name ?? null);
    this.cls.set(CLS_USER_ROLE_ID, user.role?.id ?? null);
    this.cls.set(
      CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES,
      user.role?.view_all_bookings_queries === true,
    );
    // Read-only impersonation context — the global ReadOnlyInterceptor
    // blocks every write while read_only is true; audit reads the
    // impersonator so actions trace back to the real admin.
    this.cls.set(CLS_READ_ONLY, payload.read_only === true);
    this.cls.set(CLS_IMPERSONATOR_ID, payload.impersonator_id ?? null);

    // Fetch and store permissions map for visibility scoping
    // (used by common/auth/visibility.ts to determine 'all' vs 'own')
    if (user.role?.id) {
      const permissions = await this.getRolePermissions(user.role.id, clsTenantId);
      // Convert array to map: { module -> access_level }
      const permissionsMap = permissions.reduce(
        (acc, p) => {
          acc[p.module] = p.access_level;
          return acc;
        },
        {} as Record<string, string>,
      );
      this.cls.set(CLS_USER_PERMISSIONS, permissionsMap);
    } else {
      this.cls.set(CLS_USER_PERMISSIONS, {});
    }

    return {
      id: user.id,
      email: user.email,
      name: user.name,
      tenant_id: user.tenant_id,
      role: user.role,
      read_only: payload.read_only === true,
      impersonator_id: payload.impersonator_id ?? null,
    };
  }

  private async getRolePermissions(
    roleId: string,
    tenantId: string,
  ): Promise<Array<{ module: string; access_level: string }>> {
    const cacheKey = `${JwtStrategy.PERM_CACHE_PREFIX}${tenantId}:${roleId}`;

    const cached = await this.redisService.get(cacheKey);
    if (cached) {
      return JSON.parse(cached);
    }

    const permissions = await this.rolePermRepo.find({
      where: {
        role: { id: roleId },
        tenant_id: tenantId,
        is_deleted: false,
      },
      select: {
        module: true,
        access_level: true,
      },
    });

    const result = permissions.map((p) => ({
      module: p.module,
      access_level: p.access_level,
    }));

    // Cache with same TTL as PermissionGuard (300s)
    await this.redisService.set(cacheKey, JSON.stringify(result), 300);

    return result;
  }
}
