import { AdminBookingServiceError } from '@/modules/admin-booking/services/admin-booking.service';
import { createAdminRecurringBooking } from '@/modules/admin-booking/services/admin-recurring-booking.service';
import { sendBookingConfirmation } from '@/services/booking-email.service';
import type { AppContext } from '@/types/hono';
import type { CreateRecurringBookingInput } from '@repo/api-contract';

type ComplexIdParams = { complexId: string };

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

  try {
    const group = await createAdminRecurringBooking(user.id, complexId, payload);

    const firstBooking = group.bookings[0];
    if (firstBooking?.customerEmail) {
      void sendBookingConfirmation({
        bookingCode: firstBooking.bookingCode,
        complexName: firstBooking.complexName,
        date: firstBooking.date,
        startTime: firstBooking.startTime,
        endTime: firstBooking.endTime,
        courtName: firstBooking.courtName,
        sportName: firstBooking.sport.name,
        customerName: firstBooking.customerName,
        customerEmail: firstBooking.customerEmail,
        price: firstBooking.price,
      });
    }

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