import { sseManager } from '@/lib/sse';
import {
  PublicBookingServiceError,
  createPublicBooking,
} from '@/modules/public-booking/services/public-booking.service';
import { sendBookingConfirmation } from '@/services/booking-email.service';
import type { AppContext } from '@/types/hono';
import type { CreatePublicBookingInput } from '@repo/api-contract';

type ComplexSlugParams = { complexSlug: string };

export async function createPublicBookingHandler(c: AppContext) {
  const { complexSlug } = c.req.valid('param' as never) as ComplexSlugParams;
  const payload = c.req.valid('json' as never) as CreatePublicBookingInput;

  try {
    const booking = await createPublicBooking(complexSlug, payload);

    const channel = `complex-${booking.complexId}`;
    sseManager.emit(
      channel,
      JSON.stringify({
        type: 'booking_created',
        booking: {
          id: booking.id,
          courtId: booking.courtId,
          date: booking.date,
          startTime: booking.startTime,
          endTime: booking.endTime,
        },
      })
    );

    void sendBookingConfirmation({
      bookingCode: booking.bookingCode,
      complexSlug: booking.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 PublicBookingServiceError) {
      return c.json({ message: error.message }, error.status);
    }

    throw error;
  }
}
