"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { getRazorpayClient, isRazorpayConfigured } from "@/lib/razorpay";
import { requirePermission } from "@/lib/permissions";

const BASE = "/iv-manage-84x2/payments";

function revalidateAll() {
  revalidatePath(BASE);
  revalidatePath(`${BASE}/transactions`);
  revalidatePath(`${BASE}/failed`);
  revalidatePath(`${BASE}/refunds`);
}

export async function issueRefund(formData: FormData) {
  await requirePermission("payments", "approve");
  const orderId = String(formData.get("orderId") ?? "");
  const amountRaw = String(formData.get("amount") ?? "").trim();
  const reason = String(formData.get("reason") ?? "").trim().slice(0, 500) || null;

  const order = await prisma.order.findUnique({ where: { id: orderId } });
  if (!order) redirect(`${BASE}/refunds?error=Order+not+found`);
  if (order!.status !== "paid") redirect(`${BASE}/refunds?error=Only+paid+orders+can+be+refunded`);

  const refundablePaise = order!.total - order!.refundedAmount;
  const amount = amountRaw ? Math.round(Number(amountRaw) * 100) : refundablePaise;

  if (!Number.isFinite(amount) || amount <= 0 || amount > refundablePaise) {
    redirect(`${BASE}/refunds?error=Refund+amount+must+be+between+%E2%82%B91+and+the+remaining+refundable+amount`);
  }
  if (!order!.razorpayPaymentId) {
    redirect(`${BASE}/refunds?error=This+order+has+no+recorded+payment+to+refund`);
  }

  let razorpayRefundId: string | null = null;
  if (isRazorpayConfigured()) {
    try {
      const refund = await getRazorpayClient().payments.refund(order!.razorpayPaymentId!, {
        amount,
        notes: reason ? { reason } : undefined,
      });
      razorpayRefundId = refund.id;
    } catch (err) {
      const message = err instanceof Error ? err.message : "Razorpay rejected this refund";
      redirect(`${BASE}/refunds?error=${encodeURIComponent(`Refund failed: ${message}`)}`);
    }
  }

  await prisma.order.update({
    where: { id: orderId },
    data: {
      refundedAmount: { increment: amount },
      refundReason: reason,
      razorpayRefundId,
      refundedAt: new Date(),
      refundRequestStatus: null,
    },
  });

  revalidateAll();
  revalidatePath(`/iv-manage-84x2/orders/${orderId}`);
  revalidatePath("/account");
  redirect(`${BASE}/refunds?success=Refund+issued.`);
}

export async function declineRefundRequest(orderId: string) {
  await requirePermission("payments", "approve");
  await prisma.order.update({ where: { id: orderId }, data: { refundRequestStatus: "declined" } });
  revalidateAll();
  revalidatePath("/account");
  redirect(`${BASE}/refunds?success=Refund+request+declined.`);
}
