"use server";

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

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

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

export async function createActivityAction(
  _prev: ActionState,
  formData: FormData,
): Promise<ActionState> {
  const ctx = await requireTenant();
  const raw = Object.fromEntries(formData.entries());
  const parsed = activitySchema.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.activities,
      ID.unique(),
      {
        tenantId: ctx.tenantId,
        type: data.type,
        title: data.title,
        description: data.description,
        customerId: data.customerId,
        propertyId: data.propertyId,
        dueDate: data.dueDate,
        assigneeId: data.assigneeId || ctx.user.id,
        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: "Aktivite oluşturulamadı." };
  }

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

export async function updateActivityAction(
  id: string,
  _prev: ActionState,
  formData: FormData,
): Promise<ActionState> {
  await requireTenant();
  const raw = Object.fromEntries(formData.entries());
  const parsed = activitySchema.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.activities, id, {
      type: data.type,
      title: data.title,
      description: data.description,
      customerId: data.customerId,
      propertyId: data.propertyId,
      dueDate: data.dueDate,
      assigneeId: data.assigneeId || null,
    });
  } catch {
    return { ok: false, error: "Aktivite güncellenemedi." };
  }

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

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

  try {
    await tablesDB.updateRow(DATABASE_ID, TABLES.activities, id, {
      completedAt: new Date().toISOString(),
    });
  } catch {
    return { ok: false, error: "Aktivite tamamlanamadı." };
  }

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

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

  try {
    await tablesDB.deleteRow(DATABASE_ID, TABLES.activities, id);
  } catch {
    return { ok: false, error: "Aktivite silinemedi." };
  }

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