/**
 * Test C — pgvector extension is functional end-to-end.
 *
 * Creates a temp table with a vector(3) column, inserts a row, and queries it
 * back — confirming the extension is not just registered but operational.
 *
 * Prereq: docker compose -f docker-compose.federated.yml --profile federated up -d
 * Run:    FEDERATED_INTEGRATION=1 pnpm --filter @mosaicstack/gateway test src/__tests__/integration/federated-pgvector.integration.test.ts
 *
 * Skipped when FEDERATED_INTEGRATION !== '1'.
 */

import postgres from 'postgres';
import { afterAll, describe, expect, it } from 'vitest';

const run = process.env['FEDERATED_INTEGRATION'] === '1';

const PG_URL = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';

let sql: ReturnType<typeof postgres> | undefined;

afterAll(async () => {
  if (sql) {
    await sql.end({ timeout: 2 }).catch(() => {});
  }
});

describe.skipIf(!run)('federated pgvector — functional end-to-end', () => {
  it('vector ops round-trip: INSERT [1,2,3] and SELECT returns [1,2,3]', async () => {
    sql = postgres(PG_URL, { max: 1, connect_timeout: 5, idle_timeout: 5 });

    await sql`CREATE TEMP TABLE t (id int, embedding vector(3))`;
    await sql`INSERT INTO t VALUES (1, '[1,2,3]')`;
    const rows = await sql`SELECT embedding FROM t`;

    expect(rows).toHaveLength(1);
    // The postgres driver returns vector columns as strings like '[1,2,3]'.
    // Normalise by parsing the string representation.
    const raw = rows[0]?.['embedding'] as string;
    const parsed = JSON.parse(raw) as number[];
    expect(parsed).toEqual([1, 2, 3]);
  }, 10_000);
});
