import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";

const STORE_DIR = "slack-threads";

interface SlackThread {
  channelId: string;
  threadTs: string;
}

function getStoreDir(): string {
  return resolve(process.cwd(), STORE_DIR);
}

function getStorePath(key: string): string {
  return join(getStoreDir(), `${key}.json`);
}

export function saveSlackThread(key: string, data: SlackThread): void {
  mkdirSync(getStoreDir(), { recursive: true });
  writeFileSync(getStorePath(key), JSON.stringify(data));
}

export function getSlackThread(key: string): SlackThread | null {
  const filePath = getStorePath(key);
  if (!existsSync(filePath)) return null;
  try {
    const parsed = JSON.parse(readFileSync(filePath, "utf-8")) as unknown;
    if (
      parsed &&
      typeof parsed === "object" &&
      "channelId" in parsed &&
      "threadTs" in parsed &&
      typeof (parsed as SlackThread).channelId === "string" &&
      typeof (parsed as SlackThread).threadTs === "string"
    ) {
      return parsed as SlackThread;
    }
    return null;
  } catch {
    return null;
  }
}
