"use server";

import { db } from "@/db";
import { proposals } from "@/db/schema";
import { eq, and, isNull, isNotNull } from "drizzle-orm";
import { revalidatePath } from "next/cache";

// Guard immutabilità — accepted_at è IMMUTABILE una volta valorizzato
async function getProposalForAction(slug: string) {
  const [row] = await db
    .select({ id: proposals.id, state: proposals.state, accepted_at: proposals.accepted_at })
    .from(proposals)
    .where(eq(proposals.slug, slug))
    .limit(1);
  return row ?? null;
}

export async function acceptProposal(
  slug: string,
  tier: string,
  email?: string,
  notes?: string
) {
  const proposal = await getProposalForAction(slug);
  if (!proposal) throw new Error("Proposta non trovata");
  if (proposal.accepted_at) throw new Error("Proposta già accettata");
  if (proposal.state !== "published") throw new Error("Proposta non pubblicata");
  if (!["A", "B", "C"].includes(tier)) throw new Error("Tier non valido");

  await db
    .update(proposals)
    .set({
      state: "accepted",
      selected_tier: tier,
      accepted_at: new Date(),
      client_email: email?.trim() || null,
      client_notes: notes?.trim() || null,
      updated_at: new Date(),
    })
    .where(and(eq(proposals.slug, slug), isNull(proposals.accepted_at)));

  revalidatePath(`/preventivo/${slug}`);
}

export async function rejectProposal(slug: string, notes?: string) {
  const proposal = await getProposalForAction(slug);
  if (!proposal) throw new Error("Proposta non trovata");
  if (proposal.accepted_at) throw new Error("Proposta già accettata");
  if (proposal.state !== "published") throw new Error("Proposta non pubblicata");

  await db
    .update(proposals)
    .set({
      state: "rejected",
      client_notes: notes?.trim() || null,
      updated_at: new Date(),
    })
    .where(and(eq(proposals.slug, slug), isNull(proposals.accepted_at)));

  revalidatePath(`/preventivo/${slug}`);
}
