"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 deleteDocument(id: string, reason: string): Promise<ActionResult<undefined>> {
  return run(async () => {
    await m(api.documents.remove, { id, reason });
    revalidatePath("/documents");
    revalidatePath("/customers");
    return undefined;
  });
}

/** Two-step upload: the browser PUTs the file to this URL, then calls registerDocument. */
export async function getDocumentUploadUrl(customerId?: string | null): Promise<ActionResult<{ url: string }>> {
  return run(async () => ({ url: await m(api.documents.generateUploadUrl, { customerId: customerId ?? undefined }) }));
}

export async function registerDocument(input: { storageId: string; category: string; fileName: string; mimeType: string; size: number; customerId?: string | null; reservationId?: string | null; apartmentId?: string | null; expenseId?: string | null; replacesId?: string | null }): Promise<ActionResult<{ id: string; code: string }>> {
  return run(async () => {
    const r = await m(api.documents.register, { storageId: input.storageId, category: input.category, fileName: input.fileName, mimeType: input.mimeType, size: input.size, customerId: input.customerId ?? undefined, reservationId: input.reservationId ?? undefined, apartmentId: input.apartmentId ?? undefined, expenseId: input.expenseId ?? undefined, replacesId: input.replacesId ?? undefined });
    revalidatePath("/documents");
    if (input.customerId) revalidatePath(`/customers/${input.customerId}`);
    if (input.reservationId) revalidatePath(`/reservations/${input.reservationId}`);
    if (input.apartmentId) revalidatePath(`/apartments/${input.apartmentId}`);
    return r;
  });
}
