"use server";

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

import { DATABASE_ID, TABLES } from "./schema";
import { createAdminClient } from "./server";
import { requireTenant } from "@/lib/appwrite/tenant-guard";

const investorSchema = z.object({
  name: z.string().trim().min(2, "En az 2 karakter").max(255),
  email: z.string().email("Geçerli bir email girin."),
  phone: z
    .string()
    .trim()
    .max(30)
    .optional()
    .transform((v) => v || undefined),
  budget: z
    .string()
    .optional()
    .transform((v) => (v ? Number(v) : undefined))
    .pipe(z.number().min(0).optional()),
  currency: z
    .string()
    .max(10)
    .optional()
    .transform((v) => v || undefined),
  notes: z
    .string()
    .trim()
    .max(2000)
    .optional()
    .transform((v) => v || undefined),
});

type ActionState = { ok: boolean; error?: string; fieldErrors?: Record<string, string[]> };

export async function createInvestorAction(
  _prev: ActionState,
  formData: FormData,
): Promise<ActionState> {
  const ctx = await requireTenant();
  const raw = Object.fromEntries(formData.entries());
  const parsed = investorSchema.safeParse(raw);
  if (!parsed.success) {
    return { ok: false, fieldErrors: parsed.error.flatten().fieldErrors };
  }

  const { tablesDB } = createAdminClient();
  const data = parsed.data;

  try {
    await tablesDB.createRow(
      DATABASE_ID,
      TABLES.investors,
      ID.unique(),
      {
        tenantId: ctx.tenantId,
        name: data.name,
        email: data.email,
        phone: data.phone,
        budget: data.budget,
        currency: data.currency ?? "TRY",
        notes: data.notes,
        createdBy: ctx.user.id,
      },
      [
        Permission.read(Role.team(ctx.tenantId)),
        Permission.update(Role.team(ctx.tenantId)),
        Permission.delete(Role.team(ctx.tenantId, "owner")),
        Permission.delete(Role.team(ctx.tenantId, "admin")),
      ],
    );
  } catch {
    return { ok: false, error: "Yatırımcı oluşturulamadı." };
  }

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

export async function updateInvestorAction(
  id: string,
  _prev: ActionState,
  formData: FormData,
): Promise<ActionState> {
  await requireTenant();
  const raw = Object.fromEntries(formData.entries());
  const parsed = investorSchema.safeParse(raw);
  if (!parsed.success) {
    return { ok: false, fieldErrors: parsed.error.flatten().fieldErrors };
  }

  const { tablesDB } = createAdminClient();
  const data = parsed.data;

  try {
    await tablesDB.updateRow(DATABASE_ID, TABLES.investors, id, {
      name: data.name,
      email: data.email,
      phone: data.phone,
      budget: data.budget,
      currency: data.currency,
      notes: data.notes,
    });
  } catch {
    return { ok: false, error: "Yatırımcı güncellenemedi." };
  }

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

export async function deleteInvestorAction(id: string): Promise<ActionState> {
  await requireTenant();
  const { tablesDB } = createAdminClient();

  try {
    await tablesDB.deleteRow(DATABASE_ID, TABLES.investors, id);
  } catch {
    return { ok: false, error: "Yatırımcı silinemedi." };
  }

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