import express from 'express';
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';

// Déclaration de la variable db pour qu'elle soit accessible dans tout le script
let db;

// Fonction pour initialiser la base de données
async function initializeDatabase() {
    // open the database - SQLite créera automatiquement le fichier s'il n'existe pas
    db = await open({
        filename: './datas/database.db',
        driver: sqlite3.Database
    });

    // Créer les tables nécessaires si elles n'existent pas
    await db.exec(`
      CREATE TABLE IF NOT EXISTS scores (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        player_name TEXT,
        score INTEGER,
        date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
    `);

    console.log('Database initialized');
}

initializeDatabase().catch(err => {
    console.error('Error initializing database:', err);
});

const app = express();
const port = 3001;

app.use(express.static('public'));
app.use(express.json());

app.get('/', (req, res) => {
    res.sendFile('index.html', { root: '.' });
});

app.put('/api/sendScore', (req, res) => {

    let score = req.body.score;
    let lines = req.body.lines;
    let playerName = req.body.playerName;

    // Verify the score
    if (isNaN(score) || score < 0) {
        return res.status(400).send('Invalid score');
    }

    // Verify the player name
    if (typeof playerName !== 'string' || playerName.trim() === '') {
        return res.status(400).send('Invalid player name');
    }

    // Verify the score
    if ((lines/4) * 1200 < score) {
        return res.status(400).send('Invalid score');
    }

    // Verify the number lines
    if (isNaN(lines) || lines <= 0) {
        return res.status(400).send('Invalid lines');
    }

    db.run('INSERT INTO scores (player_name, score) VALUES (?, ?)', [playerName, score])
        .then(() => {
            console.log(`Score inserted for ${playerName}`);
        })
        .then(() => {
            res.status(200).json({
                success: true,
                playerName: playerName,
                message: 'Score and history saved'
            });
        })
        .catch(err => {
            console.error('Database error:', err);
            res.status(500).send('Error inserting data');
        });
});

app.get('/api/getHighScores', async (req, res) => {
    try {
        const scores = await db.all('SELECT player_name, score FROM scores ORDER BY score DESC LIMIT 10');
        res.json(scores);
    } catch (err) {
        console.error('Database error:', err);
        res.status(500).send('Error retrieving high scores');
    }
}
);

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});
