import { z } from 'zod';
import { PaymentStatus } from '@prisma/client';
import { db } from '../../lib/prisma';
import { AppError, BadRequestError, ConflictError } from '../../lib/errors';
import { onboardStudent } from '../students/students.service';
import type { OnboardStudentInput } from '../students/students.schemas';
import { recordPayment } from '../billing/billing.service';
import { availabilityFor, checkIn, createStay, nightsBetween } from './stays.service';
import { taxedTotal } from './stays-tax';

/**
 * Group check-in (27 Oct 2026): several walk-ins who arrive together — four
 * friends, a crew — booked in one go instead of one form per bed. Each person
 * still becomes their own customer with their own stay and invoice (that is
 * what Bookings and check-out work on); the group shares one window, and one
 * payment is spread over their invoices in order.
 *
 * Every bed is checked for the whole window before anything is written, so a
 * clash stops the group cleanly rather than half-way.
 */

const payment = z.object({
  amount: z.number().int().positive(),
  method: z.enum(['CASH', 'UPI', 'CARD', 'BANK_TRANSFER', 'CHEQUE', 'OTHER']),
  // Optional for every method, as in Record payment.
  reference: z.string().trim().max(80).optional(),
  note: z.string().trim().max(200).optional(),
  paidAt: z
    .string()
    .regex(/^\d{4}-\d{2}-\d{2}$/, 'paidAt must be YYYY-MM-DD')
    .optional()
    .transform((v) => (v ? new Date(`${v}T12:00:00.000Z`) : undefined))
    .refine((d) => !d || d.getTime() <= Date.now() + 36 * 60 * 60 * 1000, 'paidAt cannot be in the future'),
});

export const groupCheckInSchema = z
  .object({
    checkIn: z.string().datetime(),
    checkOut: z.string().datetime(),
    /** Stamp the arrival straight away (walk-ins); otherwise they are booked. */
    checkInNow: z.boolean().optional(),
    members: z
      .array(
        z.object({
          studentProfileId: z.string().uuid().optional(),
          name: z.string().trim().min(2, 'Each new person needs a name').max(120).optional(),
          phone: z.string().trim().min(7).max(20).optional(),
          bedId: z.string().uuid(),
        }).refine((member) => !!member.studentProfileId || !!member.name, { message: 'Choose an existing customer or enter a new customer name', path: ['name'] }),
      )
      .min(1)
      .max(20),
    note: z.string().trim().max(300).optional(),
    payment: payment.optional(),
  })
  .refine((v) => new Set(v.members.map((m) => m.bedId)).size === v.members.length, { message: 'Two people cannot share one bed', path: ['members'] })
  .refine((v) => {
    const ids = v.members.map((member) => member.studentProfileId).filter((id): id is string => !!id);
    return new Set(ids).size === ids.length;
  }, { message: 'The same existing customer cannot be added twice', path: ['members'] })
  .refine((v) => new Date(v.checkOut) > new Date(v.checkIn), { message: 'Check-out must be after check-in', path: ['checkOut'] });

export type GroupCheckInInput = z.infer<typeof groupCheckInSchema>;

export async function groupCheckIn(input: GroupCheckInInput, actorId: string, propertyId?: string) {
  const from = new Date(input.checkIn);
  const to = new Date(input.checkOut);

  // Every bed free for the whole window, up front.
  const avail = await availabilityFor(from, to, propertyId);
  const byBed = new Map(avail.beds.map((b) => [b.bedId, b]));
  const beds = await db.bed.findMany({
    where: { id: { in: input.members.map((m) => m.bedId) }, archivedAt: null },
    select: { id: true, label: true, nightlyRent: true, room: { select: { number: true, nightlyRent: true, rateBasis: true, propertyId: true } } },
  });
  for (const m of input.members) {
    const bed = beds.find((b) => b.id === m.bedId);
    const a = byBed.get(m.bedId);
    if (!bed || !a) throw new BadRequestError('One of the beds is not in this property');
    if (!a.free) throw new ConflictError(`Room ${bed.room.number}, bed ${bed.label} is not free for those times; pick another bed`);
  }

  // A payment cannot be more than the group's stays cost, GST on top included.
  const nights = nightsBetween(from, to);
  let total = 0;
  for (const b of beds) total += await taxedTotal(b.room.propertyId, b.room.rateBasis === 'DAILY' ? nights * (b.nightlyRent ?? b.room.nightlyRent ?? 0) : 0);
  if (input.payment && input.payment.amount > total) {
    throw new BadRequestError(total ? `That is more than the ₹${total.toLocaleString('en-IN')} the group's stays cost` : 'Nothing is invoiced for these beds, so there is nothing to pay');
  }

  const requestedProfiles = input.members.map((member) => member.studentProfileId).filter((id): id is string => !!id);
  const existingProfiles = requestedProfiles.length
    ? await db.studentProfile.findMany({ where: { id: { in: requestedProfiles } }, include: { user: { select: { name: true, phone: true } } } })
    : [];
  if (existingProfiles.length !== requestedProfiles.length) throw new BadRequestError('One of the selected customers was not found');
  const existingById = new Map(existingProfiles.map((profile) => [profile.id, profile]));
  const lead = input.members[0].studentProfileId ? existingById.get(input.members[0].studentProfileId!)!.user.name : input.members[0].name!;
  const note = input.note || (input.members.length > 1 ? `Group of ${input.members.length} with ${lead}` : undefined);
  const done: { name: string; profileId: string; stayId: string; invoiceId: string | null; bed: string }[] = [];
  try {
    for (const m of input.members) {
      const existing = m.studentProfileId ? existingById.get(m.studentProfileId) : null;
      const profile = existing ?? (await onboardStudent({ name: m.name!, phone: m.phone } as OnboardStudentInput, actorId, propertyId)).profile;
      const stay = await createStay({ studentProfileId: profile.id, bedId: m.bedId, checkIn: from, checkOut: to, note }, actorId);
      if (input.checkInNow) await checkIn(stay.id, {});
      done.push({ name: existing?.user.name ?? m.name!, profileId: profile.id, stayId: stay.id, invoiceId: stay.invoiceId, bed: `${stay.bed.room.number}-${stay.bed.label}` });
    }
  } catch (err) {
    // Nothing above should fail after the checks, but if it does the desk
    // must know who is already booked rather than book them twice.
    const message = err instanceof Error ? err.message : 'Something went wrong';
    if (!done.length) throw err;
    throw new AppError(409, `${done.length} of ${input.members.length} were booked (${done.map((d) => d.name).join(', ')}) before this failed: ${message}. Book the rest one by one.`, 'GROUP_PARTLY_BOOKED');
  }

  // One payment, spread over their invoices in order.
  const paymentIds: string[] = [];
  let left = input.payment?.amount ?? 0;
  if (input.payment) {
    for (const d of done) {
      if (left <= 0 || !d.invoiceId) continue;
      const inv = await db.invoice.findFirst({ where: { id: d.invoiceId }, select: { amount: true, payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } } } });
      if (!inv) continue;
      const due = inv.amount - inv.payments.reduce((n, p) => n + p.amount, 0);
      const pay = Math.min(left, due);
      if (pay <= 0) continue;
      const r = await recordPayment(d.invoiceId, { amount: pay, method: input.payment.method, reference: input.payment.reference, note: input.payment.note ?? (done.length > 1 ? `Group payment with ${lead}` : undefined), paidAt: input.payment.paidAt }, actorId);
      paymentIds.push(r.paymentId);
      left -= pay;
    }
  }

  return { members: done, total, paid: (input.payment?.amount ?? 0) - left, paymentIds };
}
