"use server";

import { db } from "@/db";
import { bankAccounts } from "@/db/schema";
import { requireHousehold } from "@/lib/session";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";

const AddAccountSchema = z.object({
  name: z.string().min(1).max(80),
  type: z.enum(["current", "savings", "credit", "cash", "investment"]),
  balance: z.coerce.number(),
});

export async function addAccountAction(formData: FormData) {
  const { householdId, user } = await requireHousehold();
  const parsed = AddAccountSchema.parse({
    name: formData.get("name"),
    type: formData.get("type"),
    balance: formData.get("balance"),
  });
  await db.insert(bankAccounts).values({
    householdId,
    ownerUserId: user.id,
    name: parsed.name,
    type: parsed.type,
    openingBalanceMinor: Math.round(parsed.balance * 100),
    openingDate: new Date().toISOString().slice(0, 10),
    isShared: false,
  });
  revalidatePath("/onboarding");
}

export async function finishOnboardingAction() {
  await requireHousehold();
  redirect("/");
}
