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

@Injectable()
export class LabOrgGuard 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 assertLabOrganization(this.prisma, organizationId);
    return true;
  }
}
