"use server";

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

const RuleSchema = z.object({
  bankAccountId: z.string().min(1),
  categoryId: z.string().optional().nullable().or(z.literal("")),
  description: z.string().min(1).max(200),
  amount: z.coerce.number(),
  rrule: z.string().min(3),
  startDate: z.string().min(8),
  endDate: z.string().optional().nullable().or(z.literal("")),
});

export async function addRuleAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const parsed = RuleSchema.parse({
    bankAccountId: formData.get("bankAccountId"),
    categoryId: formData.get("categoryId") || null,
    description: formData.get("description"),
    amount: formData.get("amount"),
    rrule: formData.get("rrule"),
    startDate: formData.get("startDate"),
    endDate: formData.get("endDate") || null,
  });
  await db.insert(recurringRules).values({
    householdId,
    bankAccountId: parsed.bankAccountId,
    categoryId: parsed.categoryId || null,
    description: parsed.description,
    amountMinor: Math.round(parsed.amount * 100),
    rrule: parsed.rrule,
    startDate: parsed.startDate,
    endDate: parsed.endDate || null,
    isActive: true,
  });
  revalidatePath("/recurring");
  revalidatePath("/ledger");
  revalidatePath("/");
}

export async function toggleRuleAction(formData: FormData) {
  const { householdId } = await requireHousehold();
  const id = String(formData.get("id"));
  const isActive = String(formData.get("isActive")) === "true";
  await db
    .update(recurringRules)
    .set({ isActive: !isActive })
    .where(and(eq(recurringRules.id, id), eq(recurringRules.householdId, householdId)));
  revalidatePath("/recurring");
  revalidatePath("/ledger");
}

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