import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { listConversations } from '@server/services/conversations.service';

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 listConversations({
      restaurantId: restaurantId!,
      branchId: p.get('branch_id') ?? branchId ?? 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,
    });

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