"use server";

import { db } from "@/db";
import { budgets } from "@/db/schema";
import { requireHousehold } from "@/lib/session";
import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { z } from "zod";

const BudgetSchema = z.object({
  categoryId: z.string().min(1),
  amount: z.coerce.number().nonnegative(),
  period: z.enum(["weekly", "monthly", "yearly"]),
});

export async function addBudgetAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const parsed = BudgetSchema.parse({
    categoryId: formData.get("categoryId"),
    amount: formData.get("amount"),
    period: formData.get("period"),
  });
  await db.insert(budgets).values({
    householdId,
    categoryId: parsed.categoryId,
    amountMinor: Math.round(parsed.amount * 100),
    period: parsed.period,
    startDate: new Date().toISOString().slice(0, 10),
  });
  revalidatePath("/budgets");
  revalidatePath("/");
}

export async function deleteBudgetAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const id = String(formData.get("id"));
  await db.delete(budgets).where(and(eq(budgets.id, id), eq(budgets.householdId, householdId)));
  revalidatePath("/budgets");
  revalidatePath("/");
}
