"use server";

import { revalidatePath } from "next/cache";
import { z } from "zod";
import { getViewerContext } from "@/lib/auth";
import { ROLES, ROUTES } from "@/lib/constants";
import { env } from "@/lib/env";
import {
  getLocalDb,
  saveLocalDb,
  saveLocalThumbnail,
  upsertLocalDocumentMetadata,
  upsertLocalEventMetadataOverride,
} from "@/lib/local-db";
import { createClient } from "@/lib/supabase/server";
import { slugify } from "@/lib/utils";

const metadataSchema = z.object({
  sentEmailName: z.string().trim().optional(),
  approvedDocumentName: z.string().trim().optional(),
  approvedDocumentNames: z.string().trim().optional(),
  friendlyTitle: z.string().trim().optional(),
  brand: z.string().trim().optional(),
  notes: z.string().trim().optional(),
  campaignGroup: z.string().trim().optional(),
  thumbnailIntent: z.enum(["remove"]).optional(),
});

function extensionOf(fileName: string) {
  const ext = fileName.split(".").pop()?.toLowerCase();
  return ext && ext.length <= 5 ? ext : "png";
}

function parseApprovedDocumentNames(
  singleValue: string | undefined,
  encodedList: string | undefined,
) {
  const names = new Set<string>();
  if (singleValue?.trim()) {
    names.add(singleValue.trim());
  }

  if (encodedList?.trim()) {
    try {
      const parsed = JSON.parse(encodedList) as unknown;
      if (Array.isArray(parsed)) {
        for (const item of parsed) {
          const value = String(item ?? "").trim();
          if (value) names.add(value);
        }
      }
    } catch {
      // ignore malformed list and fallback to single value
    }
  }

  return [...names];
}

export async function saveMetadataAction(formData: FormData) {
  const viewer = await getViewerContext();
  const isAdmin = viewer.role === ROLES.admin;

  const parsed = metadataSchema.safeParse({
    sentEmailName: formData.get("sent_email_name"),
    approvedDocumentName: formData.get("approved_document_name"),
    approvedDocumentNames: formData.get("approved_document_names"),
    friendlyTitle: formData.get("friendly_title"),
    brand: formData.get("brand"),
    notes: formData.get("notes"),
    campaignGroup: formData.get("campaign_group"),
    thumbnailIntent: formData.get("thumbnail_intent") ?? undefined,
  });

  if (!parsed.success) {
    throw new Error(parsed.error.issues[0]?.message ?? "Invalid metadata payload.");
  }

  const { sentEmailName, approvedDocumentName, friendlyTitle, brand, notes, campaignGroup, thumbnailIntent } =
    parsed.data;
  const approvedDocumentNames = parseApprovedDocumentNames(
    approvedDocumentName,
    parsed.data.approvedDocumentNames,
  );
  const targetSentEmailName = (sentEmailName ?? "").trim();
  const targetApprovedDocumentName = approvedDocumentNames[0] ?? "";
  const targetMode = isAdmin
    ? approvedDocumentNames.length > 0
      ? "document"
      : targetSentEmailName.length > 0
        ? "event"
        : null
    : targetSentEmailName.length > 0
      ? "event"
      : null;

  if (!targetMode) {
    throw new Error(
      isAdmin
        ? "Either approved_document_name or sent_email_name is required."
        : "Regional metadata requires a sent_email_name event.",
    );
  }

  const upload = formData.get("thumbnail");
  const shouldClearThumbnail = isAdmin && thumbnailIntent === "remove";
  let thumbnailPath: string | null | undefined;

  if (!isAdmin && upload instanceof File && upload.size > 0) {
    throw new Error("Thumbnail uploads are admin-only.");
  }
  if (!isAdmin && thumbnailIntent === "remove") {
    throw new Error("Thumbnail updates are admin-only.");
  }

  if (!env.hasSupabasePublicEnv) {
    const db = await getLocalDb();

    if (!isAdmin) {
      const scopedEvent = db.raw_email_events.find(
        (event) =>
          event.sent_email_name === targetSentEmailName &&
          viewer.allowedCountries.includes(event.primary_country_code.toUpperCase()),
      );
      if (!scopedEvent) {
        throw new Error("You cannot edit metadata for this event.");
      }
    }

    if (shouldClearThumbnail) {
      thumbnailPath = null;
    } else if (isAdmin && upload instanceof File && upload.size > 0) {
      thumbnailPath = await saveLocalThumbnail(
        targetMode === "document" ? targetApprovedDocumentName : targetSentEmailName,
        upload.name,
        new Uint8Array(await upload.arrayBuffer()),
      );
    }

    if (targetMode === "document") {
      for (const documentName of approvedDocumentNames) {
        upsertLocalDocumentMetadata(db, {
          approved_document_name: documentName,
          friendly_title: friendlyTitle || null,
          brand: brand || null,
          notes: notes || null,
          campaign_group: campaignGroup || null,
          ...(thumbnailPath !== undefined ? { thumbnail_path: thumbnailPath } : {}),
        });
      }
    } else {
      upsertLocalEventMetadataOverride(db, {
        sent_email_name: targetSentEmailName,
        friendly_title: friendlyTitle || null,
        brand: brand || null,
        notes: notes || null,
        campaign_group: campaignGroup || null,
        ...(thumbnailPath !== undefined ? { thumbnail_path: thumbnailPath } : {}),
      });
    }
    await saveLocalDb(db);
  } else {
    const supabase = await createClient();

    if (!isAdmin) {
      const { data: scopedEvent, error: scopedEventError } = await supabase
        .from("raw_email_events")
        .select("sent_email_name")
        .eq("sent_email_name", targetSentEmailName)
        .maybeSingle();
      if (scopedEventError) throw new Error(scopedEventError.message);
      if (!scopedEvent) {
        throw new Error("You cannot edit metadata for this event.");
      }
    }

    if (shouldClearThumbnail) {
      thumbnailPath = null;
    } else if (isAdmin && upload instanceof File && upload.size > 0) {
      const ext = extensionOf(upload.name);
      const base = targetApprovedDocumentName || targetSentEmailName;
      const path = `${slugify(base)}-${Date.now()}.${ext}`;
      const { error: uploadError } = await supabase.storage.from("thumbnails").upload(path, upload, {
        upsert: true,
        contentType: upload.type || "image/png",
      });
      if (uploadError) throw new Error(uploadError.message);
      thumbnailPath = path;
    }

    const { error } =
      targetMode === "document"
        ? await supabase.from("email_metadata").upsert(
            approvedDocumentNames.map((documentName) => ({
              approved_document_name: documentName,
              friendly_title: friendlyTitle || null,
              brand: brand || null,
              notes: notes || null,
              campaign_group: campaignGroup || null,
              ...(thumbnailPath !== undefined ? { thumbnail_path: thumbnailPath } : {}),
            })),
            { onConflict: "approved_document_name" },
          )
        : await supabase.from("email_event_metadata_overrides").upsert(
            {
              sent_email_name: targetSentEmailName,
              friendly_title: friendlyTitle || null,
              brand: brand || null,
              notes: notes || null,
              campaign_group: campaignGroup || null,
              ...(thumbnailPath !== undefined ? { thumbnail_path: thumbnailPath } : {}),
            },
            { onConflict: "sent_email_name" },
          );

    if (error) throw new Error(error.message);
  }

  revalidatePath(ROUTES.metadata);
  revalidatePath(ROUTES.dashboard);
}
