"use server";

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { z } from "zod";
import { revalidatePath } from "next/cache";

type ActionResult = { ok: true } | { error: string };

const accountSchema = z.object({
  code: z.string().min(1, "Accounting code is required").regex(/^\d{6}$/, "Code must be exactly 6 digits (e.g. 100101)"),
  name: z.string().min(1, "Name is required"),
  description: z.string().optional(),
  parentId: z.string().optional(),
});

export async function createAccount(formData: FormData): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }

  const parsed = accountSchema.safeParse({
    code: formData.get("code"),
    name: formData.get("name"),
    description: formData.get("description") || undefined,
    parentId: (formData.get("parentId") as string) || undefined,
  });
  if (!parsed.success) return { error: parsed.error.errors[0]?.message ?? "Validation failed" };

  const data = parsed.data;
  const exists = await db.account.findUnique({ where: { code: data.code } });
  if (exists) return { error: "An accounting code with that number already exists" };

  await db.account.create({
    data: {
      code: data.code,
      name: data.name,
      description: data.description ?? null,
      parentId: data.parentId ?? null,
    },
  });
  revalidatePath("/admin/accounts");
  return { ok: true };
}

export async function updateAccount(formData: FormData): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }

  const id = formData.get("id") as string;
  if (!id) return { error: "Account ID is required" };

  const parsed = accountSchema.safeParse({
    code: formData.get("code"),
    name: formData.get("name"),
    description: formData.get("description") || undefined,
    parentId: (formData.get("parentId") as string) || undefined,
  });
  if (!parsed.success) return { error: parsed.error.errors[0]?.message ?? "Validation failed" };

  const data = parsed.data;
  const conflict = await db.account.findFirst({ where: { code: data.code, id: { not: id } } });
  if (conflict) return { error: "Another accounting code already uses that number" };

  await db.account.update({
    where: { id },
    data: {
      code: data.code,
      name: data.name,
      description: data.description ?? null,
      parentId: data.parentId ?? null,
    },
  });
  revalidatePath("/admin/accounts");
  return { ok: true };
}

export async function deleteAccount(id: string): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) return { error: "Unauthorized" };

  const inUse = await db.purchaseOrder.findFirst({ where: { accountId: id } });
  if (inUse) return { error: "Cannot delete: this code is referenced in purchase orders." };

  const hasChildren = await db.account.findFirst({ where: { parentId: id } });
  if (hasChildren) return { error: "Cannot delete: this code has sub-items. Remove those first." };

  await db.account.delete({ where: { id } });
  revalidatePath("/admin/accounts");
  return { ok: true };
}

export async function toggleAccountActive(accountId: string): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_vessels_accounts")) {
    return { error: "Unauthorized" };
  }

  const account = await db.account.findUnique({ where: { id: accountId }, select: { isActive: true } });
  if (!account) return { error: "Accounting code not found" };

  await db.account.update({ where: { id: accountId }, data: { isActive: !account.isActive } });
  revalidatePath("/admin/accounts");
  return { ok: true };
}
