// Layer 2 test: exercise server.js storage adapter against a LIVE backend.
// Complements Layer 1 (App + firebase mock) which proves App call shape but
// never touches ws.js. This catches translation bugs in the adapter.
//
// Runs the shared storage contract (same spec memory/firebase satisfy) against
// createServerStorage pointed at an ephemeral backend instance. A FRESH backend is
// spun up per test to guarantee isolation (backend has no reset endpoint yet).

'use strict';

const path = require('path');
const os = require('os');
const { createServer } = require('../index');
const { createServerStorage } = require('../../src/storage/server');
const { runStorageContract } = require('../../src/storage/contract');

// Factory: fresh backend (unique sqlite file) + storage pointed at it.
// Disposing the storage closes the backend so each test is fully isolated.
async function makeStorage({ allowDevEndpoints = false } = {}) {
  const dbPath = path.join(os.tmpdir(), `ws-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.sqlite`);
  const handle = createServer({ dbPath, port: 0, allowDevEndpoints });
  await new Promise((resolve, reject) => {
    handle.server.on('error', reject);
    handle.server.listen(0, resolve);
  });
  const port = handle.server.address().port;
  const baseUrl = `http://127.0.0.1:${port}`;
  const wsUrl = `ws://127.0.0.1:${port}/ws`;
  const storage = createServerStorage({ baseUrl, realtimeUrl: wsUrl });
  storage.dispose = (done) => handle.close(done);
  return storage;
}

runStorageContract('server (live backend)', () => makeStorage({ allowDevEndpoints: true }));

describe('server-side query constraints', () => {
  let storage;
  beforeEach(async () => {
    storage = await makeStorage();
  });
  afterEach((done) => storage.dispose(done));

  test('GET /api/collection honors orderBy + limit (server-side, not client)', async () => {
    // 5 docs with distinct ts
    for (let i = 1; i <= 5; i++) {
      await storage.addDoc('logs', { type: 'next_turn', ts: i * 100, n: i });
    }

    const res = await storage._api('GET', '/api/collection',
      { path: 'logs', orderBy: 'ts', dir: 'desc', limit: '2' });
    expect(Array.isArray(res)).toBe(true);
    expect(res.length).toBe(2);
    // desc: highest ts first
    expect(res[0].data ? res[0].data.n : res[0].n).toBe(5);
    expect(res[1].data ? res[1].data.n : res[1].n).toBe(4);
  });

  test('GET /api/collection honors offset for pagination', async () => {
    for (let i = 1; i <= 5; i++) {
      await storage.addDoc('logs', { type: 'next_turn', ts: i * 100, n: i });
    }
    // page 2 of size 2, desc by ts: should be n=3,2
    const res = await storage._api('GET', '/api/collection',
      { path: 'logs', orderBy: 'ts', dir: 'desc', limit: '2', offset: '2' });
    expect(res.length).toBe(2);
    expect(res[0].data ? res[0].data.n : res[0].n).toBe(3);
    expect(res[1].data ? res[1].data.n : res[1].n).toBe(2);
  });

  test('GET /api/collection/count returns total', async () => {
    for (let i = 1; i <= 5; i++) {
      await storage.addDoc('logs', { type: 'next_turn', ts: i * 100, n: i });
    }
    const res = await storage._api('GET', '/api/collection/count', { path: 'logs' });
    expect(res).toEqual({ count: 5 });
  });
});

describe('DELETE /api/collection (bulk delete)', () => {
  let storage;
  beforeEach(async () => {
    storage = await makeStorage({ allowDevEndpoints: true });
  });
  afterEach((done) => storage.dispose(done));

  test('deletes all docs in collection, no fetch', async () => {
    for (let i = 0; i < 3; i++) await storage.addDoc('logs', { type: 'x', n: i });
    const res = await storage._api('DELETE', '/api/collection', { path: 'logs' });
    expect(res.ok).toBe(true);
    expect(res.deleted).toBe(3);
    const after = await storage._api('GET', '/api/collection/count', { path: 'logs' });
    expect(after.count).toBe(0);
  });

  test('honors whereField filter', async () => {
    await storage.addDoc('logs', { type: 'keep', n: 1 });
    await storage.addDoc('logs', { type: 'drop', n: 2 });
    await storage.addDoc('logs', { type: 'drop', n: 3 });
    const res = await storage._api('DELETE', '/api/collection',
      { path: 'logs', whereField: 'type', whereValue: 'drop' });
    expect(res.deleted).toBe(2);
    const after = await storage._api('GET', '/api/collection/count', { path: 'logs' });
    expect(after.count).toBe(1);
  });

  test('403 when ALLOW_DEV_ENDPOINTS not set', async () => {
    const gated = await makeStorage({ allowDevEndpoints: false });
    let errMsg = null;
    try {
      await gated._api('DELETE', '/api/collection', { path: 'logs' });
    } catch (e) { errMsg = e.message; }
    expect(errMsg).toMatch(/403/);
    await new Promise((resolve) => gated.dispose(resolve));
  });
});
