import { dialog, type BrowserWindow } from "electron";
import fs from "node:fs/promises";
import path from "node:path";
import type { GoodDatabase, GoodImportFileResult, SaveResultWithPath } from "../../src/types/global.js";

export interface GoodFileService {
  exportGood: (payload: GoodDatabase) => Promise<SaveResultWithPath>;
  importGoodFile: (parentWindow?: BrowserWindow | null) => Promise<GoodImportFileResult>;
}

export function createGoodFileService(exportDirectory: string): GoodFileService {
  function exportPath(fileName: string) {
    return path.join(exportDirectory, fileName);
  }

  async function exportGood(payload: GoodDatabase): Promise<SaveResultWithPath> {
    const fileNameSafe = `good-export-${new Date().toISOString().replace(/[\\/:]/g, "-").replace(/\..+?$/, "").replace(/\s+/g, "-")}.json`;
    const filePath = exportPath(fileNameSafe);
    try {
      await fs.mkdir(path.dirname(filePath), { recursive: true });
      await fs.writeFile(filePath, JSON.stringify(payload, null, 2), "utf8");
      return { ok: true, path: filePath };
    } catch {
      return { ok: false, path: filePath };
    }
  }

  async function importGoodFile(parentWindow?: BrowserWindow | null): Promise<GoodImportFileResult> {
    const dialogOptions = {
      title: "GOOD-Datei importieren",
      properties: ["openFile"],
      filters: [{ name: "GOOD JSON", extensions: ["json"] }],
    } satisfies Electron.OpenDialogOptions;
    const dialogResult = parentWindow && !parentWindow.isDestroyed()
      ? await dialog.showOpenDialog(parentWindow, dialogOptions)
      : await dialog.showOpenDialog(dialogOptions);

    if (dialogResult.canceled || dialogResult.filePaths.length === 0) {
      return { ok: false, canceled: true, path: "" };
    }

    const filePath = dialogResult.filePaths[0];
    try {
      const text = await fs.readFile(filePath, "utf8");
      return { ok: true, canceled: false, path: filePath, database: JSON.parse(text) };
    } catch (error) {
      return {
        ok: false,
        canceled: false,
        path: filePath,
        error: error instanceof Error ? error.message : String(error),
      };
    }
  }

  return { exportGood, importGoodFile };
}
