"use server";

import { revalidatePath } from "next/cache";
import { api } from "../../../convex/_generated/api";
import { m } from "@/lib/convex-server";
import { run, type ActionResult } from "@/lib/action";

export async function recordPayment(input: { reservationId: string; amount: number; type?: string; method: string; paidAt?: string; notes?: string | null }): Promise<ActionResult<{ id: string; remaining: number }>> {
  return run(async () => {
    const r = await m(api.payments.record, { reservationId: input.reservationId, amount: Number(input.amount), type: input.type, method: input.method, paidAt: input.paidAt ? Date.parse(input.paidAt) : undefined, notes: input.notes || null });
    revalidatePath("/payments");
    revalidatePath(`/reservations/${input.reservationId}`);
    revalidatePath("/dashboard");
    return r;
  });
}

export async function reversePayment(paymentId: string, reason: string): Promise<ActionResult<undefined>> {
  return run(async () => {
    await m(api.payments.reverse, { paymentId, reason });
    revalidatePath("/payments");
    revalidatePath("/reservations");
    return undefined;
  });
}
