import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  BadRequestException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UserRole } from '@prisma/client';

export interface AuthenticatedUser {
  id: string;
  email: string;
  tenantId: string | null;
  role: UserRole;
  isActive: boolean;
}

@Injectable()
export class TenantGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user: AuthenticatedUser = request.user;

    if (!user) {
      throw new ForbiddenException('User not authenticated');
    }

    // Super admins can access all tenants
    if (user.role === UserRole.SUPER_ADMIN) {
      return true;
    }

    // Regular users (managers, staff) must have a tenant
    if (!user.tenantId) {
      throw new ForbiddenException('User does not belong to any tenant');
    }

    // Check if user is active
    if (!user.isActive) {
      throw new ForbiddenException('User account is inactive');
    }

    // For tenant-scoped operations, ensure the user can only access their tenant's data
    // This will be enforced at the service level by always using user.tenantId
    return true;
  }
}

// Decorator to mark routes that require tenant access
import { SetMetadata } from '@nestjs/common';

export const REQUIRE_TENANT_KEY = 'requireTenant';
export const RequireTenant = () => SetMetadata(REQUIRE_TENANT_KEY, true);