import type { Prisma } from '@prisma/client';
import type { PrismaService } from '../../prisma/prisma.service';

export const WALK_IN_MOBILE_PREFIX = '__walkin__:';

export function walkInMobileForOrganization(organizationId: string): string {
  return `${WALK_IN_MOBILE_PREFIX}${organizationId}`;
}

export function isWalkInMobile(mobile: string): boolean {
  return mobile.startsWith(WALK_IN_MOBILE_PREFIX);
}

type PrismaClientLike = PrismaService | Prisma.TransactionClient;

/** One sentinel Patient per clinic for treatments without a named patient. */
export async function ensureWalkInPatient(
  prisma: PrismaClientLike,
  organizationId: string,
): Promise<{ id: string; isWalkIn: true }> {
  const existing = await prisma.patient.findFirst({
    where: { createdByOrganizationId: organizationId, isWalkIn: true },
    select: { id: true },
  });
  if (existing) {
    return { id: existing.id, isWalkIn: true };
  }

  const created = await prisma.patient.create({
    data: {
      firstName: 'Walk-in',
      lastName: 'Walk-in',
      mobile: walkInMobileForOrganization(organizationId),
      isWalkIn: true,
      createdByOrganizationId: organizationId,
    },
    select: { id: true },
  });
  return { id: created.id, isWalkIn: true };
}
