import {
  CanActivate,
  ExecutionContext,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { assertClinicOrganization } from '../../common/organization-type';
import { AppException, ErrorCode } from '../errors';

@Injectable()
export class ClinicOrgGuard implements CanActivate {
  constructor(private readonly prisma: PrismaService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<{ user?: { organizationId?: string } }>();
    const organizationId = request.user?.organizationId;

    if (!organizationId) {
      throw new AppException(ErrorCode.AUTH_ORG_NOT_SELECTED, HttpStatus.UNAUTHORIZED);
    }

    await assertClinicOrganization(this.prisma, organizationId);
    return true;
  }
}
