import express from 'express';
import request from 'supertest';
import bodyParser from 'body-parser';
import { generateToken } from '../auth';
import { resetMemoryStorage } from '../storage/memory';
import statsRouter from '../routes/statsRoutes';

function buildApp() {
    const app = express();
    app.use(bodyParser.json());
    app.use('/api/stats', statsRouter);
    return app;
}

const TOKEN = `Bearer ${generateToken('testuser')}`;

beforeEach(() => {
    resetMemoryStorage();
});

test('GET /stats bez parametrů vrátí 400', async () => {
    const res = await request(buildApp())
        .get('/api/stats')
        .set('Authorization', TOKEN);
    expect(res.status).toBe(400);
});

test('GET /stats s rozsahem 4 dní vrátí 200', async () => {
    const res = await request(buildApp())
        .get('/api/stats')
        .query({ startDate: '2024-01-08', endDate: '2024-01-12' })
        .set('Authorization', TOKEN);
    expect(res.status).toBe(200);
    expect(Array.isArray(res.body)).toBe(true);
});

test('GET /stats s rozsahem nad 4 dní vrátí 400', async () => {
    const res = await request(buildApp())
        .get('/api/stats')
        .query({ startDate: '2024-01-01', endDate: '2024-01-10' })
        .set('Authorization', TOKEN);
    expect(res.status).toBe(400);
});

test('GET /stats s budoucím datem vrátí 400', async () => {
    const futureStart = '2099-01-01';
    const futureEnd = '2099-01-05';
    const res = await request(buildApp())
        .get('/api/stats')
        .query({ startDate: futureStart, endDate: futureEnd })
        .set('Authorization', TOKEN);
    expect(res.status).toBe(400);
});

test('GET /stats bez tokenu vrátí chybu', async () => {
    const res = await request(buildApp())
        .get('/api/stats')
        .query({ startDate: '2024-01-08', endDate: '2024-01-12' });
    expect(res.status).toBeGreaterThanOrEqual(400);
});
