const express = require('express');
const mysql = require('mysql2/promise');
const path = require('path');
const fileUpload = require('express-fileupload');
const app = express();

app.use(express.json({ limit: '50mb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(fileUpload());

// 1. DATABASE CONNECTION
const pool = mysql.createPool({
    socketPath: '/var/lib/mysql/mysql.sock',
    user: 'toptapli_lofhadb',
    password: 'lofhadbnewpass1',
    database: 'toptapli_lofha',
    charset: 'utf8mb4',
    waitForConnections: true,
    connectionLimit: 10
});

const ADMIN_USER = 'admin';
const ADMIN_PASS = 'Lofha2024!';

const adminAuth = (req, res, next) => {
    const authHeader = req.headers.authorization || req.headers.http_authorization || '';
    if (!authHeader.startsWith('Basic ')) {
        res.set('WWW-Authenticate', 'Basic realm="Admin"');
        return res.status(401).send('Unauthorized');
    }
    const token = authHeader.split(' ')[1];
    const ticket = Buffer.from(token, 'base64').toString();
    const [login, password] = ticket.split(':');
    if (login === ADMIN_USER && password === ADMIN_PASS) return next();
    res.status(401).send('Unauthorized');
};

// --- UNIFIED AUTH API ---
app.post('/api/auth', async (req, res) => {
    const { username, password } = req.body;
    try {
        const [users] = await pool.execute("SELECT id, username FROM users WHERE username = ? AND password = ?", [username, password]);
        if (users.length > 0) {
            return res.json(users[0]); // Flatten: Send {id:1...} not [{id:1...}]
        }
        const [result] = await pool.execute("INSERT INTO users (username, password) VALUES (?, ?)", [username, password]);
        res.json({ id: result.insertId, username });
    } catch (e) { 
        console.error(e);
        res.status(500).json({ error: "DB Error" }); 
    }
});

// --- GAME APIs ---
app.get('/api/categories', async (req, res) => {
    const [rows] = await pool.query("SELECT * FROM categories");
    res.json(rows);
});

app.post('/api/get-question', async (req, res) => {
    const { userId, category, difficulty } = req.body;
    const [rows] = await pool.execute(
        "SELECT * FROM questions WHERE category = ? AND difficulty = ? AND id NOT IN (SELECT question_id FROM seen_questions WHERE user_id = ?) ORDER BY RAND() LIMIT 1",
        [category, difficulty, userId]
    );
    if (rows.length > 0) {
        const q = rows[0]; // Flatten
        await pool.execute("INSERT INTO seen_questions (user_id, question_id) VALUES (?, ?)", [userId, q.id]);
        res.json(q);
    } else res.status(404).send("Empty");
});

app.get('/admin', adminAuth, (req, res) => res.sendFile(path.join(__dirname, 'public', 'admin.html')));
app.get('/api/admin/questions', adminAuth, async (req, res) => {
    const [rows] = await pool.query("SELECT * FROM questions ORDER BY id DESC");
    res.json(rows);
});
app.delete('/api/admin/questions/:id', adminAuth, async (req, res) => {
    await pool.execute("DELETE FROM questions WHERE id = ?", [req.params.id]);
    res.json({ success: true });
});

app.listen(process.env.PORT || 3000);
