import fs from "node:fs/promises";
import path from "node:path";
import { readDb, writeDb } from "../storage/jsondb";
import { ArchiveStatus } from "../types";
import { nowIso } from "../utils/time";
import { config } from "../config";

export const setArchiveStatus = async (status: ArchiveStatus) => {
  const db = await readDb();
  db.archives[status.hash] = status;
  await writeDb(db);
  return status;
};

export const getArchiveStatus = async (hash: string) => {
  const db = await readDb();
  const existing = db.archives[hash];
  const torrentPath = path.join(config.torrentArchiveDir, `${hash}.torrent`);
  try {
    await fs.access(torrentPath);
    if (!existing || existing.status !== "READY") {
      const updated: ArchiveStatus = {
        hash,
        status: "READY",
        torrentFilePath: torrentPath,
        source: existing?.source ?? "manual",
        updatedAt: nowIso(),
      };
      db.archives[hash] = updated;
      await writeDb(db);
      return updated;
    }
  } catch (error) {
    // File does not exist; fall back to stored status.
  }
  return existing;
};

export const createPendingArchive = async (hash: string) => {
  const status: ArchiveStatus = {
    hash,
    status: "PENDING",
    updatedAt: nowIso(),
  };
  return setArchiveStatus(status);
};
