const request = require('supertest');
const { app } = require('../../backend/server');
const { cleanDb, seedGame, seedSession, seedSessionGame } = require('../helpers/test-utils');

describe('GET /api/sessions (regression)', () => {
  beforeEach(() => {
    cleanDb();
  });

  test('GET /api/sessions/:id returns session object with preview for unauthenticated', async () => {
    const session = seedSession({ is_active: 1, notes: 'Test session' });

    const res = await request(app).get(`/api/sessions/${session.id}`);

    expect(res.status).toBe(200);
    expect(res.body).toEqual(
      expect.objectContaining({
        id: session.id,
        is_active: 1,
        has_notes: true,
        notes_preview: 'Test session',
      })
    );
    expect(res.body.notes).toBeUndefined();
    expect(res.body).toHaveProperty('games_played');
  });

  test('GET /api/sessions/:id returns 404 for nonexistent session', async () => {
    const res = await request(app).get('/api/sessions/99999');

    expect(res.status).toBe(404);
    expect(res.body.error).toBe('Session not found');
  });

  test('GET /api/sessions/:id/games returns games with expected shape', async () => {
    const game = seedGame({
      title: 'Quiplash 3',
      pack_name: 'Party Pack 7',
      min_players: 3,
      max_players: 8,
    });
    const session = seedSession({ is_active: 1 });
    seedSessionGame(session.id, game.id, { status: 'playing' });

    const res = await request(app).get(`/api/sessions/${session.id}/games`);

    expect(res.status).toBe(200);
    expect(res.body).toHaveLength(1);
    expect(res.body[0]).toEqual(
      expect.objectContaining({
        game_id: game.id,
        session_id: session.id,
        pack_name: 'Party Pack 7',
        title: 'Quiplash 3',
        min_players: 3,
        max_players: 8,
        status: 'playing',
      })
    );
    expect(res.body[0]).toHaveProperty('upvotes');
    expect(res.body[0]).toHaveProperty('downvotes');
    expect(res.body[0]).toHaveProperty('popularity_score');
  });

  test('GET /api/sessions/:id/games returns empty array for session with no games', async () => {
    const session = seedSession({ is_active: 1 });

    const res = await request(app).get(`/api/sessions/${session.id}/games`);

    expect(res.status).toBe(200);
    expect(res.body).toEqual([]);
  });
});
