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 { createOrderSchema } from '@server/validators/orders.validator';
import { listOrders, createOrder, getOrderStats } from '@server/services/orders.service';
import { notifyOrderCreated } from '@server/services/email/notify';

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

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

    if (p.get('stats') === 'true') {
      const raw = await getOrderStats(restaurantId!, branchId ?? undefined) as Record<string, string>;
      const stats = {
        totalOrders: Number(raw?.total ?? 0),
        pendingOrders: Number(raw?.pending ?? 0),
        completedOrders: Number(raw?.completed ?? 0),
        cancelledOrders: Number(raw?.cancelled ?? 0),
        totalRevenue: Number(raw?.revenue ?? 0),
      };
      return NextResponse.json({ stats });
    }

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

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

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createOrderSchema, async (req) => {
      const body = req.parsedBody as Record<string, unknown>;
      const data = { branch_id: req.session.branchId ?? null, ...body };
      const order = await createOrder(req.session.restaurantId!, data);
      try {
        const o = order as Record<string, unknown>;
        const orderRef = o.order_number ? `#${o.order_number}` : String(o.id ?? '').slice(0, 8).toUpperCase();
        const items = Array.isArray(o.items) ? (o.items as { name: string; quantity: number; price: number }[]) : [];
        await notifyOrderCreated({
          restaurantId: req.session.restaurantId!,
          branchId: (o.branch_id as string) ?? req.session.branchId ?? null,
          customerEmail: (o.customer_email as string) || null,
          customerName: String(o.customer_name ?? 'Customer'),
          orderRef,
          items,
          subtotal: Number(o.subtotal ?? 0),
          tax: Number(o.tax ?? 0),
          total: Number(o.total ?? 0),
          deliveryType: String(o.delivery_type ?? 'dine-in'),
          couponCode: (o.coupon_code as string | null) ?? null,
          discountAmount: Number(o.discount_amount ?? 0),
          loyaltyPointsRedeemed: Number(o.loyalty_points_redeemed ?? 0),
          loyaltyDiscount: Number(o.loyalty_discount ?? 0),
          giftCardApplied: Number(o.gift_card_applied ?? 0),
          giftCardRemainingBalance: o.gift_card_remaining_balance != null ? Number(o.gift_card_remaining_balance) : null,
        });
      } catch (e) { log.error({ err: e }, 'api/orders notify failed'); }
      return NextResponse.json({ order }, { status: 201 });
    })
  )
);
