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

type ComplexSlugParams = { complexSlug: string };

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

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

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

    void sendBookingCancelled({
      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,
    });

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

    throw error;
  }
}
