import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { UserRole } from '@prisma/client';
import { RequestUser } from './request-user';

@Injectable()
export class TenantGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<{
      user?: RequestUser;
      params: Record<string, string>;
      body: Record<string, unknown>;
      query: Record<string, unknown>;
    }>();
    const user = request.user;

    if (!user || user.role === UserRole.SUPER_ADMIN || user.role === UserRole.SALES_ADMIN) {
      return true;
    }

    const estateId = request.params.estateId ?? request.body.estateId ?? request.query.estateId;
    if (estateId && estateId !== user.estateId) {
      throw new ForbiddenException('Cross-estate access is not allowed');
    }

    return true;
  }
}
