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 { createCustomerSchema } from '@server/validators/customers.validator';
import { listCustomers, createCustomer } from '@server/services/customers.service';

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

    // Branch filter: explicit ?branch_id=... wins; otherwise fall back to the
    // session's active branch. Owners viewing "All branches" have branchId=null,
    // in which case we pass undefined and the list stays restaurant-wide.
    const branchOverride = p.get('branch_id');
    const effectiveBranchId = branchOverride ?? branchId ?? undefined;

    const result = await listCustomers({
      restaurantId: restaurantId!,
      branchId: effectiveBranchId,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '20', 10),
    });

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

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createCustomerSchema, async (req) => {
      const customer = await createCustomer(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ customer }, { status: 201 });
    })
  )
);
