'use strict';

// Founder-seat counter — the count is REAL active Stripe subscriptions or hidden,
// never a fabricated number and never a DB tier/founder_pricing field a comped
// profile can set without paying (security follow-up item 0). Redis mocked; the
// Stripe seat-count injected.

const request = require('supertest');

let mockStore = {};
jest.mock('../../src/utils/redis', () => ({
  getRedisClient: () => ({}),
  cacheGet: async (k) => (k in mockStore ? mockStore[k] : null),
  cacheSet: async (k, v) => { mockStore[k] = v; return true; },
  cacheDel: async () => true,
  isDegraded: () => false,
}));

const app = require('../../src/app');
const foundersRouter = require('../../src/routes/founders');

beforeEach(() => { mockStore = {}; foundersRouter.__setDeps({}); });

describe('GET /api/founders/count', () => {
  test('real active Stripe founder subs → { available, claimed, total }', async () => {
    foundersRouter.__setDeps({ countSeats: async () => 3 });
    const res = await request(app).get('/api/founders/count');
    expect(res.status).toBe(200);
    expect(res.body).toEqual({ available: true, claimed: 3, total: 100 });
  });

  test('ZERO real paid subs is shown honestly (a comped profile does not count)', async () => {
    foundersRouter.__setDeps({ countSeats: async () => 0 });
    const res = await request(app).get('/api/founders/count');
    expect(res.body).toEqual({ available: true, claimed: 0, total: 100 });
  });

  test('Stripe / founder prices unconfigured (null) → available:false, hidden', async () => {
    foundersRouter.__setDeps({ countSeats: async () => null });
    const res = await request(app).get('/api/founders/count');
    expect(res.body).toEqual({ available: false });
    expect(res.body).not.toHaveProperty('claimed');
  });

  test('Stripe throws → available:false, never fabricates', async () => {
    foundersRouter.__setDeps({ countSeats: async () => { throw new Error('stripe down'); } });
    const res = await request(app).get('/api/founders/count');
    expect(res.body).toEqual({ available: false });
  });

  test('served from cache when warm (no Stripe call)', async () => {
    mockStore['founders:count'] = { claimed: 7 };
    let called = false;
    foundersRouter.__setDeps({ countSeats: async () => { called = true; return 999; } });
    const res = await request(app).get('/api/founders/count');
    expect(res.body).toEqual({ available: true, claimed: 7, total: 100 });
    expect(called).toBe(false);
  });
});
