"use server";

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

import { logAudit } from "./audit";
import { DATABASE_ID, TABLES, type BankAccount } from "./schema";
import { createAdminClient } from "./server";
import { requireTenant } from "./tenant-guard";
import type { BankAccountActionState } from "./bank-account-types";
import { bankAccountSchema } from "@/lib/validation/bank-accounts";

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

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")),
  ];
}

function pickFormFields(formData: FormData) {
  return {
    bankName: String(formData.get("bankName") ?? "").trim(),
    accountName: String(formData.get("accountName") ?? "").trim(),
    iban: String(formData.get("iban") ?? "").trim(),
    openingBalance: String(formData.get("openingBalance") ?? "0"),
    notes: String(formData.get("notes") ?? "").trim(),
  };
}

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

  const parsed = bankAccountSchema.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.bankAccounts,
      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: "bank_account",
      entityId: row.$id,
      changes: parsed.data,
    });
  } catch (e) {
    return { ok: false, error: appwriteError(e) };
  }

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

export async function updateBankAccountAction(
  _prev: BankAccountActionState,
  formData: FormData,
): Promise<BankAccountActionState> {
  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 = bankAccountSchema.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.bankAccounts,
      id,
    )) as unknown as BankAccount;
    if (existing.tenantId !== ctx.tenantId) {
      return { ok: false, error: "Erişim engellendi." };
    }

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

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

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

export async function archiveBankAccountAction(
  formData: FormData,
): Promise<BankAccountActionState> {
  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.bankAccounts,
      id,
    )) as unknown as BankAccount;
    if (existing.tenantId !== ctx.tenantId) {
      return { ok: false, error: "Erişim engellendi." };
    }

    const newArchivedState = !existing.archived;
    await tablesDB.updateRow(DATABASE_ID, TABLES.bankAccounts, id, {
      archived: newArchivedState,
    });

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

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

export async function deleteBankAccountAction(
  formData: FormData,
): Promise<BankAccountActionState> {
  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.bankAccounts,
      id,
    )) as unknown as BankAccount;
    if (existing.tenantId !== ctx.tenantId) {
      return { ok: false, error: "Erişim engellendi." };
    }

    // Block delete if any finance_entry still references this account.
    const linked = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.financeEntries,
      queries: [
        Query.equal("tenantId", ctx.tenantId),
        Query.equal("bankAccountId", id),
        Query.limit(1),
      ],
    });
    if (linked.rows.length > 0) {
      return {
        ok: false,
        error:
          "Bu hesaba bağlı finans hareketleri var. Önce hesabı arşivleyin veya hareketleri başka bir hesaba taşıyın.",
      };
    }

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

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

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