import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { getRefundablePayments } from "@/lib/stripe";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";
import { convexQuery } from "@/lib/convex-client";

/**
 * GET /api/staff/dashboard/refunds/refundable
 * Get list of refundable payments for a customer
 */
export async function GET(request: NextRequest) {
  try {
    const user = await requireStaffAuth();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const customerId = searchParams.get("customerId");
    const refundWindowDays = parseInt(
      searchParams.get("refundWindowDays") || "180",
    );

    if (!customerId) {
      return NextResponse.json(
        { error: "customerId is required" },
        { status: 400 },
      );
    }

    // Note: Refundable payments always fetched from Stripe (source of truth for payment state).
    // The Convex getRefundablePayments query is a fallback if Stripe is unavailable.
    // Stripe path is always preferred here since it has real-time payment intent status.

    const refundablePayments = await getRefundablePayments(
      customerId,
      refundWindowDays,
    );

    // Transform for frontend
    const payments = refundablePayments.map((payment) => ({
      paymentIntentId: payment.paymentIntent.id,
      chargeId: payment.charge?.id || null,
      amount: payment.paymentIntent.amount,
      amountFormatted: (payment.paymentIntent.amount / 100).toFixed(2),
      amountRefunded: payment.amountRefunded,
      amountRefundedFormatted: (payment.amountRefunded / 100).toFixed(2),
      amountRefundable: payment.amountRefundable,
      amountRefundableFormatted: (payment.amountRefundable / 100).toFixed(2),
      currency: payment.paymentIntent.currency,
      status: payment.paymentIntent.status,
      description: payment.paymentIntent.description,
      created: new Date(payment.paymentIntent.created * 1000).toISOString(),
      isFullyRefunded: payment.isFullyRefunded,
      withinRefundWindow: payment.withinRefundWindow,
      metadata: payment.paymentIntent.metadata,
    }));

    return NextResponse.json({
      payments,
      total: payments.length,
      customerId,
      refundWindowDays,
    });
  } catch (error) {
    logger.error("Failed to fetch refundable payments:", { error });
    return NextResponse.json(
      { error: "Failed to fetch refundable payments" },
      { status: 500 },
    );
  }
}
