"use server";

import { revalidatePath } from "next/cache";
import { hasPermission } from "@/lib/adminAuth";
import { connectDB } from "@/lib/db";
import { InstagramPost } from "@/models/InstagramPost";

type FormState = { error?: string };

const INSTAGRAM_URL_RE = /^https:\/\/(www\.)?instagram\.com\/(p|reel)\/[A-Za-z0-9_-]+\/?/;

export async function createInstagramPostAction(_prev: FormState, formData: FormData): Promise<FormState> {
  if (!(await hasPermission("portfolio_create"))) return { error: "Keine Berechtigung." };
  const url = String(formData.get("url") || "").trim();
  if (!INSTAGRAM_URL_RE.test(url)) {
    return { error: "Bitte einen echten Instagram-Beitrags-Link einfügen (instagram.com/p/... oder /reel/...)." };
  }

  await connectDB();
  // Neuester Link soll immer ganz oben (= zuerst angezeigt) landen, nicht
  // hinten angehängt werden — sortOrder daher niedriger als der aktuell
  // kleinste Wert setzen, statt Date.now() (das wäre immer der größte Wert
  // und würde ganz ans Ende sortieren).
  const first = await InstagramPost.findOne({}).sort({ sortOrder: 1 }).select("sortOrder").lean();
  const sortOrder = first ? first.sortOrder - 1 : Date.now();
  await InstagramPost.create({ url, visible: true, sortOrder });

  revalidatePath("/de/admin/portfolio");
  revalidatePath("/de");
  revalidatePath("/en");
  return {};
}

export async function setInstagramPostVisibleAction(postId: string, visible: boolean) {
  if (!(await hasPermission("portfolio_edit"))) return;
  await connectDB();
  await InstagramPost.findByIdAndUpdate(postId, { visible });
  revalidatePath("/de/admin/portfolio");
  revalidatePath("/de");
  revalidatePath("/en");
}

export async function moveInstagramPostAction(postId: string, direction: "up" | "down") {
  if (!(await hasPermission("portfolio_edit"))) return;
  await connectDB();
  const item = await InstagramPost.findById(postId).lean();
  if (!item) return;

  const neighbor = await InstagramPost.findOne(
    direction === "up" ? { sortOrder: { $lt: item.sortOrder } } : { sortOrder: { $gt: item.sortOrder } }
  )
    .sort({ sortOrder: direction === "up" ? -1 : 1 })
    .lean();
  if (!neighbor) return;

  await Promise.all([
    InstagramPost.findByIdAndUpdate(item._id, { sortOrder: neighbor.sortOrder }),
    InstagramPost.findByIdAndUpdate(neighbor._id, { sortOrder: item.sortOrder }),
  ]);
  revalidatePath("/de/admin/portfolio");
  revalidatePath("/de");
  revalidatePath("/en");
}

export async function deleteInstagramPostAction(postId: string) {
  if (!(await hasPermission("portfolio_delete"))) return;
  await connectDB();
  await InstagramPost.findByIdAndDelete(postId);
  revalidatePath("/de/admin/portfolio");
  revalidatePath("/de");
  revalidatePath("/en");
}
