import i18next from "i18next";
import { Notice } from "obsidian";
import HaloService from "../service";
import { openSiteSelectionModal } from "../site-selection-modal";
import { openDeleteConfirmModal } from "../modals/delete-confirm-modal";
import type HaloPlugin from "../main";
import type { HaloSite } from "../settings";

export interface DeleteOptions {
  deleteHalo: boolean;
  deleteLocal: boolean;
}

export async function deletePost(plugin: HaloPlugin): Promise<void> {
  try {
    const { activeEditor } = plugin.app.workspace;

    if (!activeEditor || !activeEditor.file) {
      new Notice(i18next.t("common.error_no_active_editor"));
      return;
    }

    const matterData = plugin.app.metadataCache.getFileCache(activeEditor.file)?.frontmatter;

    if (!matterData?.halo?.name) {
      new Notice(i18next.t("command.delete_post.error_not_published"));
      return;
    }

    if (!matterData?.halo?.site) {
      new Notice(i18next.t("service.error_site_not_match"));
      return;
    }

    const site = plugin.settings.sites.find((s) => s.url === matterData.halo.site);

    if (!site) {
      new Notice(i18next.t("command.delete_post.error_no_matched_site"));
      return;
    }

    const title = matterData.title || activeEditor.file.basename;

    const result = await openDeleteConfirmModal(plugin, site, title, matterData.halo.name);

    if (!result.success) {
      return;
    }

    const service = new HaloService(plugin.app, plugin.settings, site);

    if (result.options.deleteHalo) {
      const success = await service.deletePost(matterData.halo.name);
      if (!success) {
        new Notice(i18next.t("service.error_delete_failed"));
        return;
      }
    }

    if (result.options.deleteLocal) {
      await plugin.app.vault.delete(activeEditor.file);
    }

    new Notice(i18next.t("service.notice_delete_success"));
  } catch (error) {
    console.error("[HaloPlugin] Delete post failed:", error);
    new Notice(i18next.t("service.error_delete_failed"));
  }
}

export async function deletePostByName(plugin: HaloPlugin, site: HaloSite, postName: string, title: string): Promise<boolean> {
  try {
    const result = await openDeleteConfirmModal(plugin, site, title, postName);

    if (!result.success) {
      return false;
    }

    const service = new HaloService(plugin.app, plugin.settings, site);

    if (result.options.deleteHalo) {
      const success = await service.deletePost(postName);
      if (!success) {
        new Notice(i18next.t("service.error_delete_failed"));
        return false;
      }
    }

    new Notice(i18next.t("service.notice_delete_success"));
    return true;
  } catch (error) {
    console.error("[HaloPlugin] Delete post by name failed:", error);
    new Notice(i18next.t("service.error_delete_failed"));
    return false;
  }
}