"use server";

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

const HouseholdSchema = z.object({ name: z.string().min(1).max(80) });

export async function renameHouseholdAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const parsed = HouseholdSchema.parse({ name: formData.get("name") });
  await db.update(households).set({ name: parsed.name }).where(eq(households.id, householdId));
  revalidatePath("/settings");
}

export async function archiveAccountAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const id = String(formData.get("id"));
  await db
    .update(bankAccounts)
    .set({ isArchived: true })
    .where(and(eq(bankAccounts.id, id), eq(bankAccounts.householdId, householdId)));
  revalidatePath("/settings");
  revalidatePath("/");
}

export async function unarchiveAccountAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const id = String(formData.get("id"));
  await db
    .update(bankAccounts)
    .set({ isArchived: false })
    .where(and(eq(bankAccounts.id, id), eq(bankAccounts.householdId, householdId)));
  revalidatePath("/settings");
  revalidatePath("/");
}
