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

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

  test('returns games with vote fields', async () => {
    seedGame({
      title: 'Quiplash 3',
      upvotes: 10,
      downvotes: 3,
      popularity_score: 7,
    });

    const res = await request(app).get('/api/games');

    expect(res.status).toBe(200);
    expect(res.body).toHaveLength(1);
    expect(res.body[0]).toEqual(
      expect.objectContaining({
        title: 'Quiplash 3',
        upvotes: 10,
        downvotes: 3,
        popularity_score: 7,
      })
    );
  });

  test('GET /api/games/:id returns vote fields', async () => {
    const game = seedGame({
      title: 'Drawful 2',
      upvotes: 5,
      downvotes: 2,
      popularity_score: 3,
    });

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

    expect(res.status).toBe(200);
    expect(res.body.upvotes).toBe(5);
    expect(res.body.downvotes).toBe(2);
    expect(res.body.popularity_score).toBe(3);
  });

  test('vote aggregates update correctly after recording votes', async () => {
    const game = seedGame({ title: 'Fibbage 4' });

    db.prepare('UPDATE games SET upvotes = upvotes + 1, popularity_score = popularity_score + 1 WHERE id = ?').run(game.id);
    db.prepare('UPDATE games SET upvotes = upvotes + 1, popularity_score = popularity_score + 1 WHERE id = ?').run(game.id);
    db.prepare('UPDATE games SET downvotes = downvotes + 1, popularity_score = popularity_score - 1 WHERE id = ?').run(game.id);

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

    expect(res.body.upvotes).toBe(2);
    expect(res.body.downvotes).toBe(1);
    expect(res.body.popularity_score).toBe(1);
  });
});
