// A1 Session 10 — /api/profiles: claim handle + publish toggle (auth) and the
// public record read. Supabase + auth are mocked (ledgerRoutes.test.js
// pattern); under test: handle validation, 409 on a taken handle,
// private-by-default writes, and the no-existence-leak 404 (unknown and
// unpublished handles are byte-identical).

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

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();
  },
}));

// Table-aware Supabase stub. Configure via mockState; every query records
// its filters so scoping is assertable.
const mockState = {
  profileRow: null, // what public_profiles maybeSingle resolves to
  upsertError: null,
  upserts: [],
  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);
  };
  b.upsert = (row, opts) => {
    mockState.upserts.push({ table, row, opts });
    return Promise.resolve({ error: mockState.upsertError });
  };
  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() {
  delete require.cache[require.resolve('../../src/routes/profiles')];
  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.upsertError = null;
  mockState.upserts.length = 0;
  mockState.ledgerRows.length = 0;
  mockState.filters.length = 0;
});

describe('GET /api/profiles/me', () => {
  test('401 without auth', async () => {
    const res = await request(mountApp()).get('/api/profiles/me');
    expect(res.status).toBe(401);
  });

  test('returns the own row scoped to the authenticated user', async () => {
    mockState.profileRow = { handle: 'kev', published: false, created_at: '2026-07-10' };
    const res = await request(mountApp())
      .get('/api/profiles/me')
      .set('Authorization', 'Bearer t');
    expect(res.status).toBe(200);
    expect(res.body.profile).toEqual({ handle: 'kev', published: false, created_at: '2026-07-10' });
    const [table, filters] = mockState.filters[0];
    expect(table).toBe('public_profiles');
    expect(filters).toContainEqual(['eq', 'user_id', 'u1']);
  });

  test('no row yet → profile null (not an error)', async () => {
    const res = await request(mountApp())
      .get('/api/profiles/me')
      .set('Authorization', 'Bearer t');
    expect(res.status).toBe(200);
    expect(res.body.profile).toBeNull();
  });
});

describe('POST /api/profiles/me', () => {
  test('401 without auth', async () => {
    const res = await request(mountApp()).post('/api/profiles/me').send({ handle: 'kev' });
    expect(res.status).toBe(401);
  });

  test.each(['ab', 'way_too_long_for_a_handle', 'has space', 'bad-dash', 'dot.dot', ''])(
    'rejects invalid handle %j with 400 and writes nothing',
    async (handle) => {
      const res = await request(mountApp())
        .post('/api/profiles/me')
        .set('Authorization', 'Bearer t')
        .send({ handle });
      expect(res.status).toBe(400);
      expect(mockState.upserts).toHaveLength(0);
    },
  );

  test('upserts own row; PRIVATE BY DEFAULT — published false unless explicitly true', async () => {
    const res = await request(mountApp())
      .post('/api/profiles/me')
      .set('Authorization', 'Bearer t')
      .send({ handle: 'Kev_2026' }); // no published flag at all
    expect(res.status).toBe(200);
    expect(res.body.profile).toEqual({ handle: 'kev_2026', published: false });
    expect(mockState.upserts).toHaveLength(1);
    expect(mockState.upserts[0].table).toBe('public_profiles');
    expect(mockState.upserts[0].row).toEqual({ user_id: 'u1', handle: 'kev_2026', published: false });
    expect(mockState.upserts[0].opts).toEqual({ onConflict: 'user_id' });
  });

  test('published only flips on an explicit boolean true', async () => {
    const res = await request(mountApp())
      .post('/api/profiles/me')
      .set('Authorization', 'Bearer t')
      .send({ handle: 'kev', published: true });
    expect(res.status).toBe(200);
    expect(mockState.upserts[0].row.published).toBe(true);

    // truthy-but-not-true must NOT publish
    const res2 = await request(mountApp())
      .post('/api/profiles/me')
      .set('Authorization', 'Bearer t')
      .send({ handle: 'kev', published: 'yes' });
    expect(res2.status).toBe(200);
    expect(mockState.upserts[1].row.published).toBe(false);
  });

  test('handle owned by another user → 409', async () => {
    mockState.upsertError = { code: '23505', message: 'duplicate key value violates unique constraint "public_profiles_handle_key"' };
    const res = await request(mountApp())
      .post('/api/profiles/me')
      .set('Authorization', 'Bearer t')
      .send({ handle: 'taken_one' });
    expect(res.status).toBe(409);
  });
});

describe('GET /api/profiles/:handle (public)', () => {
  test('published profile → handle + user-scoped aggregate + settled entries', async () => {
    mockState.profileRow = { user_id: 'u2', handle: 'kev', published: true };
    mockState.ledgerRows.push({ id: 'r1', player_name: 'Judge', outcome: 'hit', grade: 'A' });
    const res = await request(mountApp()).get('/api/profiles/kev');
    expect(res.status).toBe(200);
    expect(res.body.handle).toBe('kev');
    expect(res.body.min_sample).toBe(20);
    expect(res.body.aggregate).toBeTruthy();
    expect(res.body.aggregate.hit_pct).not.toBeUndefined();
    expect(Array.isArray(res.body.entries)).toBe(true);

    // Every ledger query is scoped to THAT user, never the public record.
    const ledgerQueries = mockState.filters.filter(([t]) => t === 'ledger_entries');
    expect(ledgerQueries.length).toBeGreaterThan(0);
    for (const [, filters] of ledgerQueries) {
      expect(filters).toContainEqual(['eq', 'user_id', 'u2']);
      expect(filters.some((f) => f[0] === 'is' && 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('NO EXISTENCE LEAK — unknown and unpublished return the identical 404', async () => {
    // Unknown handle: no row at all.
    mockState.profileRow = null;
    const unknown = await request(mountApp()).get('/api/profiles/ghost_handle');

    // Unpublished handle: row exists, published false.
    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);
  });

  test('an unpublished profile 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(res.body.aggregate).toBeUndefined();
    // The ledger table was never even queried.
    expect(mockState.filters.filter(([t]) => t === 'ledger_entries')).toHaveLength(0);
  });

  test('a malformed handle shape gets the same 404 without touching the database', async () => {
    const res = await request(mountApp()).get('/api/profiles/NOT%20A%20HANDLE');
    expect(res.status).toBe(404);
    expect(mockState.filters).toHaveLength(0);
  });
});
