// Wave 5A (D2) — the HOUSE/model /u profile. The reserved house handle
// (`vyndr`) resolves to the PUBLIC model record (user_id = NULL) WITHOUT a
// public_profiles row — the partner-pitch weapon. Every OTHER handle keeps the
// private-by-default, no-existence-leak 404 (a byte-identical body for unknown
// AND unpublished). Supabase + auth mocked (profilesRoutes.test.js pattern) —
// no network, no live Supabase.

const express = require('express');
const request = require('supertest');
const fs = require('fs');
const path = require('path');

jest.mock('../../src/middleware/auth', () => ({
  requireAuth: (req, res, next) => {
    if (!req.headers.authorization) return res.status(401).json({ error: 'auth required' });
    req.user = { id: 'u1', tier: 'analyst' };
    return next();
  },
}));

const mockState = {
  profileRow: null,
  ledgerRows: [],
  filters: [], // [table, filters[]]
};

function mockChain(table) {
  const b = { _filters: [] };
  const rec = (op) => (...args) => { b._filters.push([op, ...args]); return b; };
  b.select = () => b;
  b.eq = rec('eq');
  b.is = rec('is');
  b.not = rec('not');
  b.gte = rec('gte');
  b.gt = rec('gt');
  b.order = () => b;
  b.maybeSingle = () => {
    mockState.filters.push([table, b._filters]);
    return Promise.resolve({ data: mockState.profileRow, error: null });
  };
  b.limit = () => {
    mockState.filters.push([table, b._filters]);
    return Promise.resolve({ data: mockState.ledgerRows, error: null, count: 0 });
  };
  b.then = (resolve, reject) => {
    mockState.filters.push([table, b._filters]);
    return Promise.resolve({ data: mockState.ledgerRows, error: null, count: 0 }).then(resolve, reject);
  };
  return b;
}

jest.mock('../../src/utils/supabase', () => ({
  getSupabaseServiceClient: () => ({ from: (table) => mockChain(table) }),
}));

process.env.SUPABASE_URL = 'https://test.supabase.co';
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-key';

function mountApp() {
  // resetModules forces profiles.js to re-read process.env.HOUSE_HANDLE (jest
  // ignores require.cache deletes). The jest.mock factories re-apply.
  jest.resetModules();
  const routes = require('../../src/routes/profiles');
  const app = express();
  app.use(express.json());
  app.use('/api/profiles', routes);
  return app;
}

beforeEach(() => {
  mockState.profileRow = null;
  mockState.ledgerRows.length = 0;
  mockState.filters.length = 0;
});

describe('GET /api/profiles/vyndr — the HOUSE/model profile', () => {
  test('resolves the public user_id=NULL aggregate with NO public_profiles row', async () => {
    // Note: profileRow stays null — the house handle must NOT need a claim.
    mockState.ledgerRows.push({ id: 'r1', player_name: 'Judge', outcome: 'hit', grade: 'A', clv_result: 'beat', clv: 0.5 });
    const res = await request(mountApp()).get('/api/profiles/vyndr');

    expect(res.status).toBe(200);
    expect(res.body.handle).toBe('vyndr');
    expect(res.body.house).toBe(true);
    expect(res.body.label).toBe('VYNDR MODEL · PUBLIC RECORD');
    expect(res.body.min_sample).toBe(20);
    expect(res.body.aggregate).toBeTruthy();
    // Wave 3 per-tier calibration rides along inside the aggregate.
    expect(res.body.aggregate.by_tier).toBeDefined();
    // n<20 gate honored: hit_pct is present but null (not a small-sample %).
    expect(res.body.aggregate.hit_pct).toBeNull();
    expect(Array.isArray(res.body.entries)).toBe(true);

    // The public_profiles table was NEVER queried (handle is reserved).
    expect(mockState.filters.filter(([t]) => t === 'public_profiles')).toHaveLength(0);

    // Every ledger query is the PUBLIC record (user_id IS NULL), never a user.
    const ledgerQueries = mockState.filters.filter(([t]) => t === 'ledger_entries');
    expect(ledgerQueries.length).toBeGreaterThan(0);
    for (const [, filters] of ledgerQueries) {
      expect(filters.some((f) => f[0] === 'is' && f[1] === 'user_id' && f[2] === null)).toBe(true);
      expect(filters.some((f) => f[0] === 'eq' && f[1] === 'user_id')).toBe(false);
    }
    // The entries list is settled rows only.
    const entriesQ = ledgerQueries.find(([, f]) => f.some((x) => x[0] === 'not' && x[1] === 'outcome'));
    expect(entriesQ).toBeTruthy();
  });

  test('honors an env override for the house handle', async () => {
    const prev = process.env.HOUSE_HANDLE;
    process.env.HOUSE_HANDLE = 'house';
    try {
      const res = await request(mountApp()).get('/api/profiles/house');
      expect(res.status).toBe(200);
      expect(res.body.house).toBe(true);
      // The default handle is no longer reserved → falls through to 404.
      const other = await request(mountApp()).get('/api/profiles/vyndr');
      expect(other.status).toBe(404);
    } finally {
      if (prev === undefined) delete process.env.HOUSE_HANDLE; else process.env.HOUSE_HANDLE = prev;
    }
  });
});

describe('privacy preserved — the house handle is the ONLY special case', () => {
  test('NO EXISTENCE LEAK — unknown and unpublished USER handles are byte-identical 404s', async () => {
    mockState.profileRow = null;
    const unknown = await request(mountApp()).get('/api/profiles/ghost_handle');

    mockState.profileRow = { user_id: 'u3', handle: 'private_kev', published: false };
    const unpublished = await request(mountApp()).get('/api/profiles/private_kev');

    expect(unknown.status).toBe(404);
    expect(unpublished.status).toBe(404);
    expect(unknown.body).toEqual(unpublished.body);
    expect(unknown.body).toEqual({ error: 'Profile not found' });
  });

  test('an unpublished USER handle still leaks NO ledger data', async () => {
    mockState.profileRow = { user_id: 'u3', handle: 'private_kev', published: false };
    mockState.ledgerRows.push({ id: 'r1', player_name: 'Judge', outcome: 'hit', grade: 'A' });
    const res = await request(mountApp()).get('/api/profiles/private_kev');
    expect(res.status).toBe(404);
    expect(res.body.entries).toBeUndefined();
    expect(mockState.filters.filter(([t]) => t === 'ledger_entries')).toHaveLength(0);
  });
});

describe('/u/[handle] renders the house label + per-tier calibration', () => {
  const WEB = path.join(__dirname, '..', '..', 'web', 'src');
  const read = (rel) => fs.readFileSync(path.join(WEB, rel), 'utf8');

  it('PublicProfile shows the house label off data.house + keeps TierRecord', () => {
    const src = read('app/u/[handle]/PublicProfile.tsx');
    expect(src).toContain('VYNDR MODEL · PUBLIC RECORD');
    expect(src).toMatch(/data\.house/);
    expect(src).toContain('TierRecord');
  });

  it('has a portrait 1080x1350 share crop route', () => {
    const src = read('app/u/[handle]/portrait/route.tsx');
    expect(src).toContain('1080');
    expect(src).toContain('1350');
    expect(src).not.toContain("runtime = 'edge'");
  });

  it('is discoverable — a link to /u/vyndr on the ledger + landing record surfaces', () => {
    expect(read('app/ledger/page.tsx')).toContain('/u/vyndr');
    expect(read('app/page.tsx')).toContain('/u/vyndr');
  });
});
