import { db } from '@/lib/prisma';
import {
  AdminBookingServiceError,
  createAdminBooking,
} from '@/modules/admin-booking/services/admin-booking.service';
import { sendBookingConfirmation } from '@/services/booking-email.service';
import type { AppContext } from '@/types/hono';
import type { CreateAdminBookingInput } from '@repo/api-contract';

type ComplexIdParams = { complexId: string };

export async function createAdminBookingHandler(c: AppContext) {
  const { complexId } = c.req.valid('param' as never) as ComplexIdParams;
  const payload = c.req.valid('json' as never) as CreateAdminBookingInput;
  const user = c.get('user');

  try {
    const booking = await createAdminBooking(user.id, complexId, payload);

    const complex = await db.complex.findUnique({
      where: { id: complexId },
      select: { complexSlug: true },
    });

    void sendBookingConfirmation({
      bookingCode: booking.bookingCode,
      complexSlug: complex?.complexSlug ?? '',
      complexName: booking.complexName,
      date: booking.date,
      startTime: booking.startTime,
      endTime: booking.endTime,
      courtName: booking.courtName,
      sportName: booking.sport.name,
      customerName: booking.customerName,
      customerEmail: booking.customerEmail,
      price: booking.price,
    });

    return c.json(booking, 201);
  } catch (error) {
    if (error instanceof AdminBookingServiceError) {
      return c.json({ message: error.message }, error.status);
    }
    throw error;
  }
}
