import { Database } from "@/lib/store";
import { PinterestPinDraft } from "@/lib/types";

export type PinPreflightCheck = {
  key: string;
  label: string;
  ok: boolean;
  severity: "error" | "warning";
  detail: string;
};

export type PinPreflightResult = {
  ok: boolean;
  pinId: string;
  checks: PinPreflightCheck[];
};

const URL_PATTERN = /^https?:\/\//i;

export function preflightPinDraft(db: Database, pin: PinterestPinDraft): PinPreflightResult {
  const board = db.boards.find((item) => item.id === pin.boardId);
  const checks: PinPreflightCheck[] = [
    {
      key: "status",
      label: "发布状态",
      ok: pin.status === "scheduled" || pin.status === "published",
      severity: "error",
      detail: pin.status === "scheduled" || pin.status === "published" ? "草稿已批准进入发布队列。" : "草稿仍需人工批准。",
    },
    {
      key: "board",
      label: "图板绑定",
      ok: Boolean(board?.apiBoardId),
      severity: "error",
      detail: board?.apiBoardId ? `目标图板已绑定：${board.apiBoardId}` : "目标图板缺少 Pinterest apiBoardId。",
    },
    {
      key: "media",
      label: "媒体 URL",
      ok: Boolean(pin.mediaUrl && URL_PATTERN.test(pin.mediaUrl)),
      severity: "error",
      detail: pin.mediaUrl ? "媒体 URL 格式可用。" : "发布 Pin 必须提供图片或视频 URL。",
    },
    {
      key: "link",
      label: "落地页 URL",
      ok: !pin.link || URL_PATTERN.test(pin.link),
      severity: "warning",
      detail: pin.link ? "落地页 URL 格式可用。" : "未填写落地页，Pin 将不带站外跳转。",
    },
    {
      key: "title",
      label: "标题长度",
      ok: pin.title.trim().length > 0 && pin.title.length <= 100,
      severity: "error",
      detail: pin.title.length <= 100 ? `${pin.title.length}/100 字符。` : `标题 ${pin.title.length}/100 字符，超过 Pinterest API 限制。`,
    },
    {
      key: "description",
      label: "描述长度",
      ok: pin.description.length <= 500,
      severity: "error",
      detail: pin.description.length <= 500 ? `${pin.description.length}/500 字符。` : `描述 ${pin.description.length}/500 字符，超过 Pinterest API 限制。`,
    },
  ];

  return {
    ok: checks.every((check) => check.ok || check.severity === "warning"),
    pinId: pin.id,
    checks,
  };
}

export function summarizePreflight(result: PinPreflightResult) {
  const failed = result.checks.filter((check) => !check.ok && check.severity === "error");
  if (failed.length === 0) return "发布预检通过。";
  return `发布预检未通过：${failed.map((check) => check.label).join("、")}`;
}
