import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createBookingSchema } from '@server/validators/bookings.validator';
import { listBookings, createBooking } from '@server/services/bookings.service';
import { notifyBookingCreated } from '@server/services/email/notify';

import { childLogger } from '@server/logger';
const log = childLogger('route.bookings');

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;

    const result = await listBookings({
      restaurantId: restaurantId!,
      branchId: p.get('branch_id') ?? branchId ?? undefined,
      customerId: p.get('customer_id') ?? undefined,
      status: p.get('status') ?? undefined,
      date: p.get('date') ?? undefined,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '20', 10),
      sortField: p.get('sort_field') ?? undefined,
      sortDir: p.get('sort_dir') ?? undefined,
    });

    return NextResponse.json({ bookings: result.data, total: result.total, page: result.page, limit: result.limit, pages: result.pages });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createBookingSchema, async (req) => {
      const body = req.parsedBody as Record<string, unknown>;
      const data = { branch_id: req.session.branchId ?? null, ...body };
      const booking = await createBooking(req.session.restaurantId!, data);
      try {
        const b = booking as Record<string, unknown>;
        const id = String(b.id ?? '');
        const bookingRef = id.slice(0, 8).toUpperCase();
        await notifyBookingCreated({
          restaurantId: req.session.restaurantId!,
          branchId: (b.branch_id as string) ?? req.session.branchId ?? null,
          guestEmail: (b.guest_email as string) || null,
          guestName: String(b.guest_name ?? 'Guest'),
          bookingRef,
          date: String(b.booking_date ?? ''),
          time: String(b.booking_time ?? ''),
          partySize: Number(b.party_size ?? 1),
        });
      } catch (e) { log.error({ err: e }, 'api/bookings notify failed'); }
      return NextResponse.json({ booking }, { status: 201 });
    })
  )
);
