import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

export interface RequestTenantContext {
  userId: string;
  role: 'PLATFORM_ADMIN' | 'ORGANIZATION_ADMIN' | 'ORGANIZATION_MEMBER';
  tenantId?: string | null;
}

@Injectable()
export class TenantQueryHelper {
  constructor(private readonly prisma: PrismaService) {}

  /**
   * Enforces that the actor has a valid tenantId.
   * Per plan.md architecture rule:
   * 1. Platform Admin has no tenantId and cannot query tenant CRM data directly. Any query returns 404.
   * 2. If no tenant context is provided, fail immediately with 404 to avoid leaking data or leaking existence.
   */
  getRequiredTenantId(context?: RequestTenantContext | null): string {
    if (!context || !context.tenantId) {
      // Platform Admins have no tenantId; attempts to query tenant CRM records return 404
      throw new NotFoundException('Resource not found');
    }
    return context.tenantId;
  }

  /**
   * Scopes a WHERE clause with the tenant's tenantId.
   */
  scopeWhere<T extends Record<string, any>>(context: RequestTenantContext | null | undefined, where: T = {} as T): T & { tenantId: string } {
    const tenantId = this.getRequiredTenantId(context);
    return {
      ...where,
      tenantId,
    };
  }

  /**
   * Ensures that data to be created includes the required tenantId.
   */
  scopeCreate<T extends Record<string, any>>(context: RequestTenantContext | null | undefined, data: T): T & { tenantId: string } {
    const tenantId = this.getRequiredTenantId(context);
    return {
      ...data,
      tenantId,
    };
  }
}
