/**
 * Smoke tests: SecretBackend CRUD against live mcpd.
 *
 * Exercises the Phase 0 CLI contract end-to-end:
 *   1. `mcpctl get secretbackends` — the seeded `default` (plaintext) row exists
 *      and is marked isDefault.
 *   2. `mcpctl create secretbackend <name> --type plaintext` — create + list.
 *   3. `mcpctl describe secretbackend <name>` — sectioned output; config
 *      values that look like credentials are masked.
 *   4. `mcpctl delete secretbackend default` — fails with 409 (cannot delete
 *      the default row).
 *   5. Cleanup: delete the test row; confirm it's gone.
 *
 * Target: mcpd direct (not mcplocal). We use `--direct` so the CLI bypasses
 * mcplocal and hits mcpd at the configured URL. If mcpd is unreachable we
 * skip with a clear message — same pattern as the mcptoken smoke.
 *
 * Run with: pnpm test:smoke
 */
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import http from 'node:http';
import https from 'node:https';
import { execSync } from 'node:child_process';

const MCPD_URL = process.env.MCPD_URL ?? 'https://mcpctl.ad.itaz.eu';
const BACKEND_NAME = `smoke-sb-${Date.now().toString(36)}`;

interface CliResult { code: number; stdout: string; stderr: string }

function run(args: string): CliResult {
  try {
    const stdout = execSync(`mcpctl --direct ${args}`, {
      encoding: 'utf-8',
      timeout: 30_000,
      stdio: ['ignore', 'pipe', 'pipe'],
    });
    return { code: 0, stdout: stdout.trim(), stderr: '' };
  } catch (err) {
    const e = err as { status?: number; stdout?: Buffer | string; stderr?: Buffer | string };
    return {
      code: e.status ?? 1,
      stdout: e.stdout ? (typeof e.stdout === 'string' ? e.stdout : e.stdout.toString('utf-8')) : '',
      stderr: e.stderr ? (typeof e.stderr === 'string' ? e.stderr : e.stderr.toString('utf-8')) : '',
    };
  }
}

function healthz(url: string, timeoutMs = 5000): Promise<boolean> {
  return new Promise((resolve) => {
    const parsed = new URL(`${url.replace(/\/$/, '')}/healthz`);
    const driver = parsed.protocol === 'https:' ? https : http;
    const req = driver.get(
      {
        hostname: parsed.hostname,
        port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
        path: parsed.pathname,
        timeout: timeoutMs,
      },
      (res) => { resolve((res.statusCode ?? 500) < 500); res.resume(); },
    );
    req.on('error', () => resolve(false));
    req.on('timeout', () => { req.destroy(); resolve(false); });
  });
}

let mcpdUp = false;

describe('secretbackend smoke', () => {
  beforeAll(async () => {
    mcpdUp = await healthz(MCPD_URL);
    if (!mcpdUp) {
      // eslint-disable-next-line no-console
      console.warn(`\n  ○ secretbackend smoke: skipped — ${MCPD_URL}/healthz unreachable. Set MCPD_URL to override.\n`);
    }
  }, 20_000);

  afterAll(() => {
    if (!mcpdUp) return;
    run(`delete secretbackend ${BACKEND_NAME}`);
  });

  it('lists at least one secretbackend with a default flagged', () => {
    if (!mcpdUp) return;
    // The seeded `plaintext` backend is the bootstrap default, but operators
    // routinely promote a remote backend (openbao etc.) to default once it's
    // healthy. Asserting a specific *name* here is implementation detail —
    // the invariant we care about is that exactly one row is the default.
    const result = run('get secretbackends -o json');
    expect(result.code, result.stderr).toBe(0);
    const rows = JSON.parse(result.stdout) as Array<{ name: string; type: string; isDefault: boolean }>;
    expect(rows.length).toBeGreaterThan(0);
    const defaults = rows.filter((r) => r.isDefault === true);
    expect(defaults, 'exactly one default backend must exist').toHaveLength(1);
    expect(['plaintext', 'openbao']).toContain(defaults[0]!.type);
  });

  it('creates a plaintext backend and round-trips it through describe', () => {
    if (!mcpdUp) return;
    // Idempotent cleanup in case a prior run left debris
    run(`delete secretbackend ${BACKEND_NAME}`);

    const created = run(`create secretbackend ${BACKEND_NAME} --type plaintext --description smoke-test`);
    expect(created.code, created.stderr || created.stdout).toBe(0);
    expect(created.stdout).toMatch(new RegExp(`secretbackend '${BACKEND_NAME}'`));

    const described = run(`describe secretbackend ${BACKEND_NAME}`);
    expect(described.code, described.stderr).toBe(0);
    expect(described.stdout).toContain(`=== SecretBackend: ${BACKEND_NAME} ===`);
    expect(described.stdout).toContain('Type:');
    expect(described.stdout).toContain('plaintext');
    expect(described.stdout).toContain('smoke-test');
  });

  it('refuses to delete the seeded default backend', () => {
    if (!mcpdUp) return;
    // Find whichever row is currently the default — we don't hard-code the name
    // because operators may have renamed or swapped it.
    const listed = run('get secretbackends -o json');
    expect(listed.code).toBe(0);
    const rows = JSON.parse(listed.stdout) as Array<{ name: string; isDefault: boolean }>;
    const def = rows.find((r) => r.isDefault);
    expect(def).toBeDefined();

    const del = run(`delete secretbackend ${def!.name}`);
    // 409 surfaces as exit 1 with a descriptive error. The exact wording has
    // changed across releases ("is the default", "is in use", "cannot delete",
    // "is still referenced by N secret(s); migrate them first") — accept any
    // refusal that mentions one of: default, in use, cannot delete, referenced.
    expect(del.code).toBe(1);
    const combined = (del.stderr + del.stdout).toLowerCase();
    expect(combined).toMatch(/default|in use|cannot delete|referenced/);
  });

  it('round-trips get -o yaml → apply -f', () => {
    if (!mcpdUp) return;
    const yaml = run(`get secretbackend ${BACKEND_NAME} -o yaml`);
    expect(yaml.code).toBe(0);
    // Apply-compatible output must start with `kind: secretbackend`
    expect(yaml.stdout).toMatch(/kind:\s+secretbackend/);
    expect(yaml.stdout).toContain(`name: ${BACKEND_NAME}`);
    expect(yaml.stdout).toContain('type: plaintext');
  });

  it('deletes the test backend and confirms it is gone', () => {
    if (!mcpdUp) return;
    const del = run(`delete secretbackend ${BACKEND_NAME}`);
    expect(del.code, del.stderr).toBe(0);

    const listed = run('get secretbackends -o json');
    const rows = JSON.parse(listed.stdout) as Array<{ name: string }>;
    expect(rows.find((r) => r.name === BACKEND_NAME)).toBeUndefined();
  });
});
