import { afterEach, describe, expect, it } from 'vitest';
import Database from 'better-sqlite3';
import { mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { Repository } from './repository.js';

/**
 * Phase 8 (API-key auth + user-owned MCP servers) added auth_kind /
 * static_token_enc / auth_header_name / owner_id to mcp_servers via migrate.ts.
 * These must also exist on the fresh-DB path (schema.sql, run by
 * Repository.initSchema) — otherwise a DB created without runMigrations lacks
 * the columns. This guards the dual-path rule (project_db_migration_dual_path).
 */

function hasColumn(db: Database.Database, table: string, column: string): boolean {
  const cols = db.prepare(`PRAGMA table_info('${table}')`).all() as Array<{ name: string }>;
  return cols.some((c) => c.name === column);
}

describe('mcp_servers auth columns: Repository.initSchema (schema.sql)', () => {
  let tempDir = '';

  afterEach(() => {
    if (tempDir) {
      rmSync(tempDir, { recursive: true, force: true });
      tempDir = '';
    }
  });

  function makeRepo(): Repository {
    tempDir = mkdtempSync(join(tmpdir(), 'maestro-mcpauth-'));
    return new Repository(join(tempDir, 'orchestrator.db'));
  }

  it('has auth_kind / static_token_enc / auth_header_name / owner_id on a fresh Repository', () => {
    const db = makeRepo().getDb();
    expect(hasColumn(db, 'mcp_servers', 'auth_kind')).toBe(true);
    expect(hasColumn(db, 'mcp_servers', 'static_token_enc')).toBe(true);
    expect(hasColumn(db, 'mcp_servers', 'auth_header_name')).toBe(true);
    expect(hasColumn(db, 'mcp_servers', 'owner_id')).toBe(true);
  });
});
