import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, chmodSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';

export interface StoredCredentials {
  token: string;
  mcpdUrl: string;
  user: string;
  expiresAt?: string;
}

export interface CredentialsDeps {
  configDir: string;
}

function defaultConfigDir(): string {
  return join(homedir(), '.mcpctl');
}

function credentialsPath(deps?: Partial<CredentialsDeps>): string {
  return join(deps?.configDir ?? defaultConfigDir(), 'credentials');
}

export function saveCredentials(creds: StoredCredentials, deps?: Partial<CredentialsDeps>): void {
  const dir = deps?.configDir ?? defaultConfigDir();
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true });
  }
  const path = credentialsPath(deps);
  writeFileSync(path, JSON.stringify(creds, null, 2) + '\n', 'utf-8');
  chmodSync(path, 0o600);
}

export function loadCredentials(deps?: Partial<CredentialsDeps>): StoredCredentials | null {
  const path = credentialsPath(deps);
  if (!existsSync(path)) {
    return null;
  }
  const raw = readFileSync(path, 'utf-8');
  return JSON.parse(raw) as StoredCredentials;
}

export function deleteCredentials(deps?: Partial<CredentialsDeps>): boolean {
  const path = credentialsPath(deps);
  if (!existsSync(path)) {
    return false;
  }
  unlinkSync(path);
  return true;
}
