"use server";

import { revalidatePath } from "next/cache";
import { AppwriteException, ID, Permission, Role } from "node-appwrite";
import { z } from "zod";

import { logAudit } from "./audit";
import { DATABASE_ID, TABLES, type Service } from "./schema";
import { createAdminClient } from "./server";
import { requireTenant } from "./tenant-guard";
import type { ServiceActionState } from "./service-types";
import { serviceSchema } from "@/lib/validation/services";

function appwriteError(e: unknown): string {
  if (e instanceof AppwriteException) {
    return e.message || "Beklenmeyen bir hata oluştu.";
  }
  return "Bağlantı hatası. Tekrar deneyin.";
}

function pickFormFields(formData: FormData) {
  return {
    customerId: String(formData.get("customerId") ?? ""),
    name: String(formData.get("name") ?? "").trim(),
    description: String(formData.get("description") ?? "").trim(),
    unitPrice: String(formData.get("unitPrice") ?? "0"),
    currency: (formData.get("currency") as "TRY" | "USD" | "EUR" | null) ?? "TRY",
    recurring: formData.get("recurring") ?? false,
    billingPeriod: (formData.get("billingPeriod") as "monthly" | "yearly" | "onetime" | null) ??
      "onetime",
    assigneeIds: formData.getAll("assigneeIds").map(String).filter(Boolean),
  };
}

function flattenErrors(err: z.ZodError): Record<string, string> {
  const out: Record<string, string> = {};
  for (const issue of err.issues) {
    const key = issue.path.join(".");
    if (key && !out[key]) out[key] = issue.message;
  }
  return out;
}

function teamRowPermissions(tenantId: string) {
  return [
    Permission.read(Role.team(tenantId)),
    Permission.update(Role.team(tenantId)),
    Permission.delete(Role.team(tenantId, "owner")),
    Permission.delete(Role.team(tenantId, "admin")),
  ];
}

export async function createServiceAction(
  _prev: ServiceActionState,
  formData: FormData,
): Promise<ServiceActionState> {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    return { ok: false, error: "Yetkiniz yok." };
  }

  const parsed = serviceSchema.safeParse(pickFormFields(formData));
  if (!parsed.success) {
    return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
  }

  try {
    const { tablesDB } = createAdminClient();
    const row = await tablesDB.createRow(
      DATABASE_ID,
      TABLES.services,
      ID.unique(),
      {
        tenantId: ctx.tenantId,
        createdBy: ctx.user.id,
        ...parsed.data,
      },
      teamRowPermissions(ctx.tenantId),
    );

    await logAudit({
      tenantId: ctx.tenantId,
      userId: ctx.user.id,
      action: "create",
      entityType: "service",
      entityId: row.$id,
      changes: parsed.data,
    });
  } catch (e) {
    return { ok: false, error: appwriteError(e) };
  }

  revalidatePath("/services");
  return { ok: true };
}

export async function updateServiceAction(
  _prev: ServiceActionState,
  formData: FormData,
): Promise<ServiceActionState> {
  const id = String(formData.get("id") ?? "");
  if (!id) return { ok: false, error: "ID eksik." };

  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    return { ok: false, error: "Yetkiniz yok." };
  }

  const parsed = serviceSchema.safeParse(pickFormFields(formData));
  if (!parsed.success) {
    return { ok: false, error: "Form geçersiz.", fieldErrors: flattenErrors(parsed.error) };
  }

  try {
    const { tablesDB } = createAdminClient();
    const existing = (await tablesDB.getRow(
      DATABASE_ID,
      TABLES.services,
      id,
    )) as unknown as Service;

    if (existing.tenantId !== ctx.tenantId) {
      return { ok: false, error: "Erişim engellendi." };
    }

    await tablesDB.updateRow(DATABASE_ID, TABLES.services, id, parsed.data);

    await logAudit({
      tenantId: ctx.tenantId,
      userId: ctx.user.id,
      action: "update",
      entityType: "service",
      entityId: id,
      changes: parsed.data,
    });
  } catch (e) {
    return { ok: false, error: appwriteError(e) };
  }

  revalidatePath("/services");
  return { ok: true };
}

export async function deleteServiceAction(formData: FormData): Promise<ServiceActionState> {
  const id = String(formData.get("id") ?? "");
  if (!id) return { ok: false, error: "ID eksik." };

  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    return { ok: false, error: "Yetkiniz yok." };
  }

  try {
    const { tablesDB } = createAdminClient();
    const existing = (await tablesDB.getRow(
      DATABASE_ID,
      TABLES.services,
      id,
    )) as unknown as Service;

    if (existing.tenantId !== ctx.tenantId) {
      return { ok: false, error: "Erişim engellendi." };
    }

    await tablesDB.deleteRow(DATABASE_ID, TABLES.services, id);

    await logAudit({
      tenantId: ctx.tenantId,
      userId: ctx.user.id,
      action: "delete",
      entityType: "service",
      entityId: id,
      changes: { name: existing.name },
    });
  } catch (e) {
    return { ok: false, error: appwriteError(e) };
  }

  revalidatePath("/services");
  return { ok: true };
}
