"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 CalendarEvent } from "./schema";
import { createAdminClient } from "./server";
import { requireTenant } from "./tenant-guard";
import type { CalendarActionState } from "./calendar-types";
import { calendarEventSchema } from "@/lib/validation/calendar";

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 {
    title: String(formData.get("title") ?? "").trim(),
    description: String(formData.get("description") ?? "").trim(),
    start: String(formData.get("start") ?? ""),
    end: String(formData.get("end") ?? ""),
    allDay: formData.get("allDay") ?? false,
    customerId: String(formData.get("customerId") ?? ""),
    color: String(formData.get("color") ?? ""),
  };
}

function toIso(v: string, allDay: boolean | undefined): string {
  if (!v) return v;
  // datetime-local => "YYYY-MM-DDTHH:mm"; date => "YYYY-MM-DD"
  if (/^\d{4}-\d{2}-\d{2}$/.test(v)) {
    return `${v}T00:00:00.000+00:00`;
  }
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(v)) {
    return new Date(v).toISOString();
  }
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(v)) {
    return new Date(v).toISOString();
  }
  // fallback for already-iso
  return v;
}

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

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

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

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

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

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

    const data = {
      ...parsed.data,
      start: toIso(parsed.data.start, parsed.data.allDay),
      end: toIso(parsed.data.end, parsed.data.allDay),
    };
    await tablesDB.updateRow(DATABASE_ID, TABLES.calendarEvents, id, data);

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

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

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

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

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

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