import i18next from "i18next";
import { Notice, requestUrl } from "obsidian";
import { openSiteSelectionModal } from "../site-selection-modal";
import type HaloPlugin from "../main";
import type { Post, Snapshot } from "../services/types";

export async function exportPostAsMarkdown(plugin: HaloPlugin, postName: string, title: string): Promise<void> {
  try {
    let site = plugin.settings.sites[0];
    if (plugin.settings.sites.length > 1) {
      site = await openSiteSelectionModal(plugin);
    }

    const headers = {
      Authorization: `Bearer ${site.token}`,
    };

    const snapshot = (await requestUrl({
      url: `${site.url}/apis/uc.api.content.halo.run/v1alpha1/posts/${postName}/draft?patched=true`,
      headers,
    }).json) as Snapshot;

    const { "content.halo.run/patched-raw": raw } = snapshot?.metadata?.annotations || {};

    if (!raw) {
      new Notice(i18next.t("export.error_no_content"));
      return;
    }

    const content = `---
title: ${title}
---

${raw}`;

    const fileName = `${title}.md`;
    const file = await plugin.app.vault.create(fileName, content);

    plugin.app.workspace.getLeaf().openFile(file);

    new Notice(i18next.t("export.notice_export_success", { fileName }));
  } catch (error) {
    console.error("[HaloPlugin] Export as markdown failed:", error);
    new Notice(i18next.t("export.error_export_failed"));
  }
}

export async function exportPostAsJson(plugin: HaloPlugin, postName: string, title: string): Promise<void> {
  try {
    let site = plugin.settings.sites[0];
    if (plugin.settings.sites.length > 1) {
      site = await openSiteSelectionModal(plugin);
    }

    const headers = {
      Authorization: `Bearer ${site.token}`,
    };

    const post = (await requestUrl({
      url: `${site.url}/apis/uc.api.content.halo.run/v1alpha1/posts/${postName}`,
      headers,
    }).json) as Post;

    const snapshot = (await requestUrl({
      url: `${site.url}/apis/uc.api.content.halo.run/v1alpha1/posts/${postName}/draft?patched=true`,
      headers,
    }).json) as Snapshot;

    const exportData = {
      post: post,
      content: {
        raw: snapshot?.metadata?.annotations?.["content.halo.run/patched-raw"] || "",
        content: snapshot?.metadata?.annotations?.["content.halo.run/patched-content"] || "",
        rawType: snapshot?.spec?.rawType || "markdown",
      },
      exportedAt: new Date().toISOString(),
    };

    const fileName = `${title}.json`;
    const file = await plugin.app.vault.create(fileName, JSON.stringify(exportData, null, 2));

    plugin.app.workspace.getLeaf().openFile(file);

    new Notice(i18next.t("export.notice_export_success", { fileName }));
  } catch (error) {
    console.error("[HaloPlugin] Export as JSON failed:", error);
    new Notice(i18next.t("export.error_export_failed"));
  }
}