"use server";

import { revalidatePath } from "next/cache";
import { requireDashboardContext } from "@/core/auth/dashboard-context";
import {
  addCustomDomainSchema,
  createCategorySchema,
  createJournalSchema,
  createProjectSchema,
  createServiceSchema,
  updateMediaAltSchema,
  updateProfileSchema,
} from "@/core/validation/schemas";
import {
  createAward,
  deleteAward,
} from "@/services/award-service";
import {
  createPublication,
  deletePublication,
} from "@/services/publication-service";
import {
  createTeamMember,
  deleteTeamMember,
} from "@/services/team-service";
import { writeAuditLog } from "@/services/audit-service";
import {
  createCategory,
  deleteCategory,
  updateCategory,
} from "@/services/category-service";
import {
  addCustomDomain,
  deleteCustomDomain,
} from "@/services/domain-service";
import {
  archiveJournalPost,
  createJournalPost,
  publishJournalPost,
  softDeleteJournalPost,
  updateJournalPost,
} from "@/services/journal-service";
import {
  deleteInquiry,
  updateInquiryStatus,
  type InquiryStatus,
} from "@/services/inquiry-service";
import {
  deleteProjectMedia,
  updateProjectMediaAlt,
} from "@/services/media-service";
import {
  archiveProject,
  createProject,
  publishProject,
  setProjectHeroImage,
  softDeleteProject,
  updateProject,
} from "@/services/project-service";
import { updateArchitectProfile } from "@/services/profile-service";
import {
  createService,
  deleteService,
  toggleServicePublish,
  updateService,
} from "@/services/studio-services-service";

export type ActionResult =
  | { ok: true; id?: string }
  | { ok: false; error: string };

function parseCategoryId(formData: FormData): string | null | undefined {
  const raw = String(formData.get("categoryId") ?? "").trim();
  if (!raw) return null;
  return raw;
}

function parseProjectFields(formData: FormData) {
  const yearRaw = String(formData.get("year") ?? "").trim();
  return createProjectSchema.safeParse({
    title: String(formData.get("title") ?? ""),
    slug: String(formData.get("slug") ?? "") || undefined,
    description: String(formData.get("description") ?? "") || undefined,
    location: String(formData.get("location") ?? "") || undefined,
    year: yearRaw ? Number(yearRaw) : undefined,
    area: String(formData.get("area") ?? "") || undefined,
    clientName: String(formData.get("clientName") ?? "") || undefined,
    architectCredit: String(formData.get("architectCredit") ?? "") || undefined,
    projectType: String(formData.get("projectType") ?? "") || undefined,
    concept: String(formData.get("concept") ?? "") || undefined,
    designProcess: String(formData.get("designProcess") ?? "") || undefined,
    materials: String(formData.get("materials") ?? "") || undefined,
    videoUrl: String(formData.get("videoUrl") ?? "") || undefined,
    isFeatured3d: formData.get("isFeatured3d") === "on",
    categoryId: parseCategoryId(formData),
    seoTitle: String(formData.get("seoTitle") ?? "") || undefined,
    seoDescription: String(formData.get("seoDescription") ?? "") || undefined,
  });
}

export async function createProjectAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("projects:create");
    const parsed = parseProjectFields(formData);

    if (!parsed.success) {
      return { ok: false, error: "Validation failed" };
    }

    const project = await createProject(ctx.tenant, parsed.data);
    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "project.create",
      targetType: "project",
      targetId: project?.id,
    });

    revalidatePath("/dashboard/projects");
    revalidatePath("/site");
    return { ok: true, id: project?.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to create project";
    return { ok: false, error: message };
  }
}

export async function updateProjectAction(
  projectId: string,
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("projects:edit");
    const parsed = parseProjectFields(formData);

    if (!parsed.success) {
      return { ok: false, error: "Validation failed" };
    }

    const updated = await updateProject(ctx.tenant, projectId, parsed.data);
    if (!updated) return { ok: false, error: "Project not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "project.update",
      targetType: "project",
      targetId: projectId,
    });

    revalidatePath("/dashboard/projects");
    revalidatePath(`/dashboard/projects/${projectId}`);
    revalidatePath("/site");
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to update project";
    return { ok: false, error: message };
  }
}

export async function updateProfileAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("settings:manage");
    const yearRaw = String(formData.get("foundedYear") ?? "").trim();
    const parsed = updateProfileSchema.safeParse({
      studioName: String(formData.get("studioName") ?? ""),
      description: String(formData.get("description") ?? "") || undefined,
      tagline: String(formData.get("tagline") ?? "") || undefined,
      about: String(formData.get("about") ?? "") || undefined,
      architectName: String(formData.get("architectName") ?? "") || undefined,
      architectTitle: String(formData.get("architectTitle") ?? "") || undefined,
      philosophy: String(formData.get("philosophy") ?? "") || undefined,
      vision: String(formData.get("vision") ?? "") || undefined,
      mission: String(formData.get("mission") ?? "") || undefined,
      approach: String(formData.get("approach") ?? "") || undefined,
      designPrinciples:
        String(formData.get("designPrinciples") ?? "") || undefined,
      experience: String(formData.get("experience") ?? "") || undefined,
      studioCulture: String(formData.get("studioCulture") ?? "") || undefined,
      workspace: String(formData.get("workspace") ?? "") || undefined,
      methodology: String(formData.get("methodology") ?? "") || undefined,
      collaborations: String(formData.get("collaborations") ?? "") || undefined,
      location: String(formData.get("location") ?? "") || undefined,
      foundedYear: yearRaw ? Number(yearRaw) : null,
      websiteUrl: String(formData.get("websiteUrl") ?? ""),
      publicEmail: String(formData.get("publicEmail") ?? "") || undefined,
      phone: String(formData.get("phone") ?? "") || undefined,
      whatsapp: String(formData.get("whatsapp") ?? "") || undefined,
      businessHours: String(formData.get("businessHours") ?? "") || undefined,
      mapEmbedUrl: String(formData.get("mapEmbedUrl") ?? "") || undefined,
      socialInstagram:
        String(formData.get("socialInstagram") ?? "") || undefined,
      socialLinkedin: String(formData.get("socialLinkedin") ?? "") || undefined,
      socialX: String(formData.get("socialX") ?? "") || undefined,
      seoTitle: String(formData.get("seoTitle") ?? "") || undefined,
      seoDescription: String(formData.get("seoDescription") ?? "") || undefined,
    });

    if (!parsed.success) {
      return { ok: false, error: "Validation failed" };
    }

    const {
      socialInstagram,
      socialLinkedin,
      socialX,
      ...profileData
    } = parsed.data;

    await updateArchitectProfile(ctx.tenant, {
      ...profileData,
      socialLinks: {
        ...(socialInstagram ? { instagram: socialInstagram } : {}),
        ...(socialLinkedin ? { linkedin: socialLinkedin } : {}),
        ...(socialX ? { x: socialX } : {}),
      },
    });
    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "profile.update",
      targetType: "architect_profile",
      targetId: ctx.tenant.tenantId,
    });

    revalidatePath("/dashboard/settings");
    revalidatePath("/dashboard");
    revalidatePath("/site");
    return { ok: true };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to update profile";
    return { ok: false, error: message };
  }
}

export async function createServiceAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("services:manage");
    const sortRaw = String(formData.get("sortOrder") ?? "").trim();
    const parsed = createServiceSchema.safeParse({
      title: String(formData.get("title") ?? ""),
      slug: String(formData.get("slug") ?? "") || undefined,
      description: String(formData.get("description") ?? "") || undefined,
      sortOrder: sortRaw ? Number(sortRaw) : undefined,
      isPublished: formData.get("isPublished") === "on",
    });
    if (!parsed.success) return { ok: false, error: "Validation failed" };

    const row = await createService(ctx.tenant, parsed.data);
    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "service.create",
      targetType: "service",
      targetId: row?.id,
    });
    revalidatePath("/dashboard/services");
    revalidatePath("/site");
    return { ok: true, id: row?.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to create service";
    return { ok: false, error: message };
  }
}

export async function updateServiceAction(
  serviceId: string,
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("services:manage");
    const sortRaw = String(formData.get("sortOrder") ?? "").trim();
    const parsed = createServiceSchema.safeParse({
      title: String(formData.get("title") ?? ""),
      slug: String(formData.get("slug") ?? "") || undefined,
      description: String(formData.get("description") ?? "") || undefined,
      sortOrder: sortRaw ? Number(sortRaw) : undefined,
      isPublished: formData.get("isPublished") === "on",
    });
    if (!parsed.success) return { ok: false, error: "Validation failed" };

    const updated = await updateService(ctx.tenant, serviceId, parsed.data);
    if (!updated) return { ok: false, error: "Service not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "service.update",
      targetType: "service",
      targetId: serviceId,
    });
    revalidatePath("/dashboard/services");
    revalidatePath(`/dashboard/services/${serviceId}`);
    revalidatePath("/site");
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to update service";
    return { ok: false, error: message };
  }
}

export async function deleteServiceAction(
  serviceId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("services:manage");
  await deleteService(ctx.tenant, serviceId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "service.delete",
    targetType: "service",
    targetId: serviceId,
  });
  revalidatePath("/dashboard/services");
  revalidatePath("/site");
}

export async function createCategoryAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("projects:edit");
    const sortRaw = String(formData.get("sortOrder") ?? "").trim();
    const parsed = createCategorySchema.safeParse({
      name: String(formData.get("name") ?? ""),
      slug: String(formData.get("slug") ?? "") || undefined,
      description: String(formData.get("description") ?? "") || undefined,
      sortOrder: sortRaw ? Number(sortRaw) : undefined,
    });
    if (!parsed.success) return { ok: false, error: "Validation failed" };

    const row = await createCategory(ctx.tenant, parsed.data);
    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "category.create",
      targetType: "project_category",
      targetId: row?.id,
    });
    revalidatePath("/dashboard/categories");
    revalidatePath("/dashboard/projects");
    return { ok: true, id: row?.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to create category";
    return { ok: false, error: message };
  }
}

export async function updateCategoryAction(
  categoryId: string,
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("projects:edit");
    const sortRaw = String(formData.get("sortOrder") ?? "").trim();
    const parsed = createCategorySchema.safeParse({
      name: String(formData.get("name") ?? ""),
      slug: String(formData.get("slug") ?? "") || undefined,
      description: String(formData.get("description") ?? "") || undefined,
      sortOrder: sortRaw ? Number(sortRaw) : undefined,
    });
    if (!parsed.success) return { ok: false, error: "Validation failed" };

    const updated = await updateCategory(ctx.tenant, categoryId, parsed.data);
    if (!updated) return { ok: false, error: "Category not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "category.update",
      targetType: "project_category",
      targetId: categoryId,
    });
    revalidatePath("/dashboard/categories");
    revalidatePath("/dashboard/projects");
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to update category";
    return { ok: false, error: message };
  }
}

export async function deleteCategoryAction(
  categoryId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("projects:edit");
  await deleteCategory(ctx.tenant, categoryId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "category.delete",
    targetType: "project_category",
    targetId: categoryId,
  });
  revalidatePath("/dashboard/categories");
  revalidatePath("/dashboard/projects");
}

export async function createJournalAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("journal:manage");
    const parsed = createJournalSchema.safeParse({
      title: String(formData.get("title") ?? ""),
      slug: String(formData.get("slug") ?? "") || undefined,
      excerpt: String(formData.get("excerpt") ?? "") || undefined,
      content: String(formData.get("content") ?? "") || undefined,
      seoTitle: String(formData.get("seoTitle") ?? "") || undefined,
      seoDescription: String(formData.get("seoDescription") ?? "") || undefined,
    });
    if (!parsed.success) return { ok: false, error: "Validation failed" };

    const row = await createJournalPost(ctx.tenant, parsed.data);
    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "journal.create",
      targetType: "journal_post",
      targetId: row?.id,
    });
    revalidatePath("/dashboard/journal");
    revalidatePath("/site");
    return { ok: true, id: row?.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to create journal post";
    return { ok: false, error: message };
  }
}

export async function updateJournalAction(
  postId: string,
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("journal:manage");
    const parsed = createJournalSchema.safeParse({
      title: String(formData.get("title") ?? ""),
      slug: String(formData.get("slug") ?? "") || undefined,
      excerpt: String(formData.get("excerpt") ?? "") || undefined,
      content: String(formData.get("content") ?? "") || undefined,
      seoTitle: String(formData.get("seoTitle") ?? "") || undefined,
      seoDescription: String(formData.get("seoDescription") ?? "") || undefined,
    });
    if (!parsed.success) return { ok: false, error: "Validation failed" };

    const updated = await updateJournalPost(ctx.tenant, postId, parsed.data);
    if (!updated) return { ok: false, error: "Post not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "journal.update",
      targetType: "journal_post",
      targetId: postId,
    });
    revalidatePath("/dashboard/journal");
    revalidatePath(`/dashboard/journal/${postId}`);
    revalidatePath("/site");
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to update journal post";
    return { ok: false, error: message };
  }
}

export async function publishJournalAction(
  postId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("journal:manage");
  await publishJournalPost(ctx.tenant, postId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "journal.publish",
    targetType: "journal_post",
    targetId: postId,
  });
  revalidatePath("/dashboard/journal");
  revalidatePath("/site");
}

export async function archiveJournalAction(
  postId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("journal:manage");
  await archiveJournalPost(ctx.tenant, postId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "journal.archive",
    targetType: "journal_post",
    targetId: postId,
  });
  revalidatePath("/dashboard/journal");
  revalidatePath("/site");
}

export async function deleteJournalAction(
  postId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("journal:manage");
  await softDeleteJournalPost(ctx.tenant, postId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "journal.delete",
    targetType: "journal_post",
    targetId: postId,
  });
  revalidatePath("/dashboard/journal");
  revalidatePath("/site");
}

export async function publishProjectAction(
  projectId: string,
  _formData?: FormData,
): Promise<void> {
  await publishProjectMutate(projectId);
}

async function publishProjectMutate(projectId: string): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("projects:publish");
    const updated = await publishProject(ctx.tenant, projectId);
    if (!updated) return { ok: false, error: "Project not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "project.publish",
      targetType: "project",
      targetId: projectId,
    });

    revalidatePath("/dashboard/projects");
    revalidatePath("/site");
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to publish project";
    return { ok: false, error: message };
  }
}

export async function archiveProjectAction(
  projectId: string,
  _formData?: FormData,
): Promise<void> {
  await archiveProjectMutate(projectId);
}

async function archiveProjectMutate(projectId: string): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("projects:edit");
    const updated = await archiveProject(ctx.tenant, projectId);
    if (!updated) return { ok: false, error: "Project not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "project.archive",
      targetType: "project",
      targetId: projectId,
    });

    revalidatePath("/dashboard/projects");
    revalidatePath("/site");
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to archive project";
    return { ok: false, error: message };
  }
}

export async function deleteProjectAction(
  projectId: string,
  _formData?: FormData,
): Promise<void> {
  await deleteProjectMutate(projectId);
}

async function deleteProjectMutate(projectId: string): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("projects:delete");
    const updated = await softDeleteProject(ctx.tenant, projectId);
    if (!updated) return { ok: false, error: "Project not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "project.delete",
      targetType: "project",
      targetId: projectId,
    });

    revalidatePath("/dashboard/projects");
    revalidatePath("/site");
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to delete project";
    return { ok: false, error: message };
  }
}

export async function updateInquiryStatusAction(
  inquiryId: string,
  status: InquiryStatus,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("inquiries:manage");
    const updated = await updateInquiryStatus(ctx.tenant, inquiryId, status);
    if (!updated) return { ok: false, error: "Inquiry not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "inquiry.status_update",
      targetType: "inquiry",
      targetId: inquiryId,
      metadata: { status },
    });

    revalidatePath("/dashboard/inquiries");
    revalidatePath(`/dashboard/inquiries/${inquiryId}`);
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to update inquiry";
    return { ok: false, error: message };
  }
}

export async function deleteInquiryAction(
  inquiryId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("inquiries:manage");
  await deleteInquiry(ctx.tenant, inquiryId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "inquiry.delete",
    targetType: "inquiry",
    targetId: inquiryId,
  });
  revalidatePath("/dashboard/inquiries");
}

export async function deleteMediaAction(
  mediaId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("media:manage");
  const deleted = await deleteProjectMedia(ctx.tenant, mediaId);
  if (!deleted) return;

  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "media.delete",
    targetType: "project_media",
    targetId: mediaId,
    metadata: { projectId: deleted.projectId },
  });

  revalidatePath("/dashboard/media");
  revalidatePath(`/dashboard/projects/${deleted.projectId}`);
  revalidatePath("/dashboard/projects");
  revalidatePath("/dashboard");
}

export async function updateMediaAltAction(
  mediaId: string,
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("media:manage");
    const parsed = updateMediaAltSchema.safeParse({
      altText: String(formData.get("altText") ?? ""),
    });
    if (!parsed.success) return { ok: false, error: "Validation failed" };

    const updated = await updateProjectMediaAlt(
      ctx.tenant,
      mediaId,
      parsed.data.altText ?? "",
    );
    if (!updated) return { ok: false, error: "Media not found" };

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "media.update",
      targetType: "project_media",
      targetId: mediaId,
    });

    revalidatePath("/dashboard/media");
    revalidatePath(`/dashboard/projects/${updated.projectId}`);
    return { ok: true, id: updated.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to update media";
    return { ok: false, error: message };
  }
}

export async function setProjectHeroAction(
  projectId: string,
  mediaId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("projects:edit");
  await setProjectHeroImage(ctx.tenant, projectId, mediaId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "project.hero_set",
    targetType: "project",
    targetId: projectId,
    metadata: { mediaId },
  });
  revalidatePath(`/dashboard/projects/${projectId}`);
  revalidatePath("/dashboard/projects");
  revalidatePath("/dashboard");
  revalidatePath("/site");
}

export async function toggleServicePublishAction(
  serviceId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("services:manage");
  await toggleServicePublish(ctx.tenant, serviceId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "service.toggle_publish",
    targetType: "service",
    targetId: serviceId,
  });
  revalidatePath("/dashboard/services");
  revalidatePath(`/dashboard/services/${serviceId}`);
  revalidatePath("/site");
}

export async function addDomainAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("domains:manage");
    const parsed = addCustomDomainSchema.safeParse({
      domain: String(formData.get("domain") ?? ""),
    });
    if (!parsed.success) return { ok: false, error: "Invalid domain" };

    const row = await addCustomDomain(ctx.tenant, parsed.data.domain);
    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "domain.create",
      targetType: "domain",
      targetId: row?.id,
    });
    revalidatePath("/dashboard/domains");
    return { ok: true, id: row?.id };
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Failed to add domain";
    return { ok: false, error: message };
  }
}

export async function deleteDomainAction(
  domainId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("domains:manage");
  await deleteCustomDomain(ctx.tenant, domainId);
  await writeAuditLog({
    actorUserId: ctx.user.id,
    tenantId: ctx.tenant.tenantId,
    action: "domain.delete",
    targetType: "domain",
    targetId: domainId,
  });
  revalidatePath("/dashboard/domains");
}

export async function createAwardAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("settings:manage");
    const yearRaw = String(formData.get("year") ?? "").trim();
    const row = await createAward(ctx.tenant, {
      title: String(formData.get("title") ?? ""),
      organization: String(formData.get("organization") ?? "") || undefined,
      year: yearRaw ? Number(yearRaw) : null,
      category: String(formData.get("category") ?? "") || undefined,
      description: String(formData.get("description") ?? "") || undefined,
    });
    revalidatePath("/dashboard/awards");
    revalidatePath("/site");
    return { ok: true, id: row?.id };
  } catch (error) {
    return {
      ok: false,
      error: error instanceof Error ? error.message : "Failed to create award",
    };
  }
}

export async function deleteAwardAction(
  awardId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("settings:manage");
  await deleteAward(ctx.tenant, awardId);
  revalidatePath("/dashboard/awards");
  revalidatePath("/site");
}

export async function createTeamMemberAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("settings:manage");
    const row = await createTeamMember(ctx.tenant, {
      name: String(formData.get("name") ?? ""),
      slug: String(formData.get("slug") ?? "") || undefined,
      role: String(formData.get("role") ?? "") || undefined,
      bio: String(formData.get("bio") ?? "") || undefined,
      email: String(formData.get("email") ?? "") || undefined,
    });
    revalidatePath("/dashboard/team");
    revalidatePath("/site");
    return { ok: true, id: row?.id };
  } catch (error) {
    return {
      ok: false,
      error:
        error instanceof Error ? error.message : "Failed to create team member",
    };
  }
}

export async function deleteTeamMemberAction(
  memberId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("settings:manage");
  await deleteTeamMember(ctx.tenant, memberId);
  revalidatePath("/dashboard/team");
  revalidatePath("/site");
}

export async function createPublicationAction(
  formData: FormData,
): Promise<ActionResult> {
  try {
    const ctx = await requireDashboardContext("settings:manage");
    const yearRaw = String(formData.get("year") ?? "").trim();
    const row = await createPublication(ctx.tenant, {
      title: String(formData.get("title") ?? ""),
      publisher: String(formData.get("publisher") ?? "") || undefined,
      year: yearRaw ? Number(yearRaw) : null,
      url: String(formData.get("url") ?? "") || undefined,
      kind: String(formData.get("kind") ?? "") || undefined,
      description: String(formData.get("description") ?? "") || undefined,
    });
    revalidatePath("/dashboard/publications");
    revalidatePath("/site");
    return { ok: true, id: row?.id };
  } catch (error) {
    return {
      ok: false,
      error:
        error instanceof Error ? error.message : "Failed to create publication",
    };
  }
}

export async function deletePublicationAction(
  publicationId: string,
  _formData?: FormData,
): Promise<void> {
  const ctx = await requireDashboardContext("settings:manage");
  await deletePublication(ctx.tenant, publicationId);
  revalidatePath("/dashboard/publications");
  revalidatePath("/site");
}
