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';
import { getUsage } from '@server/services/billing.service';
import { requirePlanFeature, getPlanLimits } from '@server/utils/features';
import { AppError } from '@server/errors';
import { createWidgetConversation } from '@server/services/widget.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requirePlanFeature(restaurantId!, 'chat_agent');
    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 });
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    await requirePlanFeature(restaurantId!, 'chat_agent');

    // Enforce conversations_per_month using the canonical billing usage source
    const [limits, usage] = await Promise.all([
      getPlanLimits(restaurantId!),
      getUsage(restaurantId!),
    ]);

    if (limits.conversations_per_month !== null && usage.conversations >= limits.conversations_per_month) {
      throw new AppError(
        `Monthly conversation limit of ${limits.conversations_per_month} reached. Upgrade your plan to continue.`,
        402,
        'PLAN_LIMIT_EXCEEDED'
      );
    }

    const body = await req.json().catch(() => ({}));
    const customerName = (body as { customer_name?: string }).customer_name || 'Website Visitor';
    const agentId = (body as { agent_id?: string }).agent_id || null;

    const conversation = await createWidgetConversation(restaurantId!, customerName, agentId);
    return NextResponse.json({ conversation }, { status: 201 });
  })
);
