"use server";

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

const GoalSchema = z.object({
  name: z.string().min(1).max(80),
  targetAmount: z.coerce.number().nonnegative(),
  currentAmount: z.coerce.number().nonnegative().default(0),
  targetDate: z.string().optional().nullable().or(z.literal("")),
  monthlyContribution: z.coerce.number().nonnegative().default(0),
  annualInterestRatePct: z.coerce.number().nonnegative().default(0),
});

export async function addGoalAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const parsed = GoalSchema.parse({
    name: formData.get("name"),
    targetAmount: formData.get("targetAmount"),
    currentAmount: formData.get("currentAmount") ?? 0,
    targetDate: formData.get("targetDate") || null,
    monthlyContribution: formData.get("monthlyContribution") ?? 0,
    annualInterestRatePct: formData.get("annualInterestRatePct") ?? 0,
  });
  await db.insert(savingsGoals).values({
    householdId,
    name: parsed.name,
    targetAmountMinor: Math.round(parsed.targetAmount * 100),
    currentAmountMinor: Math.round(parsed.currentAmount * 100),
    targetDate: parsed.targetDate || null,
    monthlyContributionMinor: Math.round(parsed.monthlyContribution * 100),
    annualInterestRate: Math.round(parsed.annualInterestRatePct * 100), // basis points
  });
  revalidatePath("/goals");
}

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