import { app, safeStorage } from "electron";
import fs from "node:fs/promises";
import path from "node:path";
import type { PersistedSession } from "./session";

type SessionFile =
  | {
      version: 1;
      encrypted: true;
      data: string;
    }
  | {
      version: 1;
      encrypted: false;
      data: PersistedSession;
    };

export class SessionStore {
  async load(): Promise<PersistedSession | undefined> {
    try {
      const raw = await fs.readFile(this.filePath(), "utf8");
      const parsed = JSON.parse(raw) as SessionFile;
      if (parsed.encrypted) {
        const decrypted = safeStorage.decryptString(Buffer.from(parsed.data, "base64"));
        return JSON.parse(decrypted) as PersistedSession;
      }
      return parsed.data;
    } catch {
      return undefined;
    }
  }

  async save(session: PersistedSession): Promise<void> {
    await fs.mkdir(path.dirname(this.filePath()), { recursive: true });
    if (!safeStorage.isEncryptionAvailable()) {
      await this.clear();
      return;
    }

    const raw = JSON.stringify(session);
    const payload: SessionFile = {
      version: 1,
      encrypted: true,
      data: safeStorage.encryptString(raw).toString("base64")
    };

    await fs.writeFile(this.filePath(), JSON.stringify(payload, null, 2), "utf8");
  }

  async clear(): Promise<void> {
    await fs.rm(this.filePath(), { force: true });
  }

  filePath(): string {
    return path.join(app.getPath("userData"), "session.json");
  }
}
