import { describe, it, expect, beforeEach, afterEach } from "vitest";
import fs from "fs";
import os from "os";
import path from "path";
import { listCredentials, getCredential } from "../src/modules/credentials.js";

let tmpDir: string;

beforeEach(() => {
  tmpDir = path.join(os.tmpdir(), "treehouse-test-" + Math.random().toString(36).slice(2));
  fs.mkdirSync(tmpDir, { recursive: true });
});

afterEach(() => {
  fs.rmSync(tmpDir, { recursive: true, force: true });
});

describe("listCredentials", () => {
  it("returns empty array when credentials.json is missing", async () => {
    const result = await listCredentials(tmpDir);
    expect(result).toEqual([]);
  });

  it("returns parsed credentials from credentials.json", async () => {
    const creds = [
      { name: "API_KEY", value: "secret123", description: "My API key" },
      { name: "DB_PASS", value: "pass456" },
    ];
    fs.writeFileSync(path.join(tmpDir, "credentials.json"), JSON.stringify(creds));
    const result = await listCredentials(tmpDir);
    expect(result).toHaveLength(2);
    expect(result[0].name).toBe("API_KEY");
    expect(result[1].name).toBe("DB_PASS");
  });
});

describe("getCredential", () => {
  it("returns a specific credential by name", async () => {
    const creds = [
      { name: "API_KEY", value: "secret123", description: "My API key" },
      { name: "DB_PASS", value: "pass456" },
    ];
    fs.writeFileSync(path.join(tmpDir, "credentials.json"), JSON.stringify(creds));
    const cred = await getCredential("API_KEY", tmpDir);
    expect(cred).toEqual({ name: "API_KEY", value: "secret123", description: "My API key" });
  });

  it("throws when credential not found", async () => {
    fs.writeFileSync(path.join(tmpDir, "credentials.json"), JSON.stringify([]));
    await expect(getCredential("NONEXISTENT", tmpDir)).rejects.toThrow("Credential not found: NONEXISTENT");
  });
});
