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';

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);
      return NextResponse.json({ order }, { status: 201 });
    })
  )
);
