"use server";

import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { db } from "@/db";
import {
  equipmentCategories,
  equipmentCategoryMerkmale,
} from "@/db/schema";
import { requirePlatformAdmin } from "@/lib/auth/guards";
import { writeAudit } from "@/lib/audit";
import {
  equipmentCategoryCreateSchema,
  equipmentCategoryUpdateSchema,
  categoryMerkmalSchema,
} from "@/lib/validation/equipment-category";
import { uuidSchema } from "@/lib/validation/common";

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

export async function createCategory(input: unknown): Promise<ActionResult> {
  const s = await requirePlatformAdmin();
  const p = equipmentCategoryCreateSchema.safeParse(input);
  if (!p.success) {
    return { ok: false, error: p.error.issues[0]?.message ?? "Ungültige Eingabe." };
  }
  await db.transaction(async (tx) => {
    const [c] = await tx
      .insert(equipmentCategories)
      .values({ name: p.data.name })
      .returning();
    if (!c) throw new Error("Kategorie konnte nicht angelegt werden.");
    await writeAudit(s.user.id, "category.create", "equipment_category", c.id, undefined, tx);
  });
  revalidatePath("/admin/geraete-kategorien");
  return { ok: true };
}

export async function updateCategory(input: unknown): Promise<ActionResult> {
  const s = await requirePlatformAdmin();
  const p = equipmentCategoryUpdateSchema.safeParse(input);
  if (!p.success) {
    return { ok: false, error: p.error.issues[0]?.message ?? "Ungültige Eingabe." };
  }
  await db.transaction(async (tx) => {
    await tx
      .update(equipmentCategories)
      .set({ name: p.data.name })
      .where(eq(equipmentCategories.id, p.data.id));
    await writeAudit(s.user.id, "category.update", "equipment_category", p.data.id, undefined, tx);
  });
  revalidatePath(`/admin/geraete-kategorien/${p.data.id}`);
  return { ok: true };
}

export async function setCategoryMerkmal(input: {
  categoryId: unknown;
  merkmal: unknown;
}): Promise<ActionResult> {
  const s = await requirePlatformAdmin();
  const cid = uuidSchema.safeParse(input.categoryId);
  const m = categoryMerkmalSchema.safeParse(input.merkmal);
  if (!cid.success || !m.success) return { ok: false, error: "Ungültige Eingabe." };
  await db.transaction(async (tx) => {
    await tx
      .insert(equipmentCategoryMerkmale)
      .values({
        categoryId: cid.data,
        merkmalId: m.data.merkmalId,
        reihenfolge: m.data.reihenfolge,
      })
      .onConflictDoUpdate({
        target: [
          equipmentCategoryMerkmale.categoryId,
          equipmentCategoryMerkmale.merkmalId,
        ],
        set: { reihenfolge: m.data.reihenfolge },
      });
    await writeAudit(
      s.user.id,
      "category.merkmal_set",
      "equipment_category",
      cid.data,
      { merkmalId: m.data.merkmalId },
      tx,
    );
  });
  revalidatePath(`/admin/geraete-kategorien/${cid.data}`);
  return { ok: true };
}

export async function removeCategoryMerkmal(input: {
  categoryId: unknown;
  merkmalId: unknown;
}): Promise<ActionResult> {
  const s = await requirePlatformAdmin();
  const cid = uuidSchema.safeParse(input.categoryId);
  const mid = uuidSchema.safeParse(input.merkmalId);
  if (!cid.success || !mid.success) return { ok: false, error: "Ungültige ID." };
  await db.transaction(async (tx) => {
    await tx
      .delete(equipmentCategoryMerkmale)
      .where(
        and(
          eq(equipmentCategoryMerkmale.categoryId, cid.data),
          eq(equipmentCategoryMerkmale.merkmalId, mid.data),
        ),
      );
    await writeAudit(
      s.user.id,
      "category.merkmal_remove",
      "equipment_category",
      cid.data,
      { merkmalId: mid.data },
      tx,
    );
  });
  revalidatePath(`/admin/geraete-kategorien/${cid.data}`);
  return { ok: true };
}
