import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { listRedemptions, listRedemptionsAll } from '@server/services/coupons.service';
import { requirePlanFeature } from '@server/utils/features';

function csvEscape(v: unknown): string {
  if (v === null || v === undefined) return '';
  const s = String(v);
  if (/[",\n\r]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
  return s;
}

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'coupons');
    await requirePlanFeature(req.session.restaurantId!, 'coupons');
    const { id } = await ctx.params;
    const url = new URL(req.url);
    const restaurantId = req.session.restaurantId!;

    if ((url.searchParams.get('format') ?? '').toLowerCase() === 'csv') {
      const rows = await listRedemptionsAll(id, restaurantId);
      const headers = [
        'redemption_id', 'created_at', 'order_number', 'order_id',
        'channel', 'discount_amount', 'order_total',
        'customer_id', 'customer_name', 'customer_phone',
      ];
      const lines = [headers.join(',')];
      for (const r of rows) {
        lines.push([
          r.id, r.created_at, r.order_number ?? '', r.order_id ?? '',
          r.channel, r.discount_amount, r.order_total ?? '',
          r.customer_id ?? '', r.customer_name ?? '', r.customer_phone ?? '',
        ].map(csvEscape).join(','));
      }
      const csv = lines.join('\n') + '\n';
      return new Response(csv, {
        status: 200,
        headers: {
          'Content-Type': 'text/csv; charset=utf-8',
          'Content-Disposition': `attachment; filename="coupon-${id}-redemptions.csv"`,
        },
      });
    }

    const page = parseInt(url.searchParams.get('page') ?? '1', 10);
    const limit = parseInt(url.searchParams.get('limit') ?? '50', 10);
    const result = await listRedemptions(id, restaurantId, page, limit);
    return NextResponse.json(result);
  })
);
