import fs from "node:fs/promises";
import path from "node:path";
import type { SnapshotRepositoryPort } from "./contracts.js";
import type { SaveResultWithPath } from "../../src/types/global.js";
import type { AppSnapshot } from "../../src/types/domain.js";

export class JsonSnapshotRepository implements SnapshotRepositoryPort {
  private readonly filePath: string;

  constructor(userDataPath: string, fileName = "snapshot.json") {
    this.filePath = path.join(userDataPath, fileName);
  }

  async load() {
    try {
      return JSON.parse(await fs.readFile(this.filePath, "utf8")) as AppSnapshot;
    } catch {
      return null;
    }
  }

  async save(snapshot: AppSnapshot): Promise<SaveResultWithPath> {
    await fs.mkdir(path.dirname(this.filePath), { recursive: true });
    await fs.writeFile(this.filePath, JSON.stringify(snapshot, null, 2), "utf8");
    return { ok: true, path: this.filePath };
  }
}
