const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const bcrypt = require('bcryptjs');

const app = express();
app.use(express.json());
app.use(cors());

// --- Database Configuration ---
// IMPORTANT: Update 'password' to your real MySQL password. 
// If you have no password, use an empty string: password: ''
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '', 
    database: 'LibraryDB'
});

// Connect to Database
db.connect((err) => {
    if (err) {
        console.error('❌ Database connection failed: ' + err.stack);
        return;
    }
    console.log('✅ Connected to MySQL as id ' + db.threadId);
});

// --- Authentication ---
app.post('/register', async (req, res) => {
    const { username, password } = req.body;
    try {
        const hashedPassword = await bcrypt.hash(password, 10);
        db.query('INSERT INTO Users (Username, Password) VALUES (?, ?)', [username, hashedPassword], (err) => {
            if (err) return res.status(400).json({ error: "Registration failed: " + err.message });
            res.json({ message: "User registered successfully" });
        });
    } catch (e) { res.status(500).json({ error: "Server error" }); }
});

app.post('/login', (req, res) => {
    const { username, password } = req.body;
    db.query('SELECT * FROM Users WHERE Username = ?', [username], async (err, results) => {
        if (err) return res.status(500).json({ error: "Database error" });
        if (results.length === 0) return res.status(401).json({ error: "Invalid username or password" });

        const isMatch = await bcrypt.compare(password, results[0].Password);
        if (!isMatch) return res.status(401).json({ error: "Invalid username or password" });

        res.json({ message: "Login successful", userID: results[0].UserID });
    });
});

// --- Generic CRUD Helper ---
const handleQuery = (query, params, res) => {
    db.query(query, params, (err, results) => {
        if (err) return res.status(500).json({ error: err.message });
        res.json(results);
    });
};

// --- CRUD Routes ---
app.get('/books', (req, res) => handleQuery('SELECT * FROM Book', [], res));
app.post('/books', (req, res) => handleQuery('INSERT INTO Book (Title) VALUES (?)', [req.body.Title], res));
app.put('/books/:id', (req, res) => handleQuery('UPDATE Book SET Title = ? WHERE BookID = ?', [req.body.Title, req.params.id], res));
app.delete('/books/:id', (req, res) => handleQuery('DELETE FROM Book WHERE BookID = ?', [req.params.id], res));

app.get('/members', (req, res) => handleQuery('SELECT * FROM Member', [], res));
app.post('/members', (req, res) => handleQuery('INSERT INTO Member (Name) VALUES (?)', [req.body.Name], res));
app.put('/members/:id', (req, res) => handleQuery('UPDATE Member SET Name = ? WHERE MemberID = ?', [req.body.Name, req.params.id], res));
app.delete('/members/:id', (req, res) => handleQuery('DELETE FROM Member WHERE MemberID = ?', [req.params.id], res));

app.get('/borrows', (req, res) => handleQuery('SELECT * FROM Borrow', [], res));
app.post('/borrows', (req, res) => handleQuery('INSERT INTO Borrow (BookID, MemberID, BorrowDate) VALUES (?, ?, ?)', [req.body.BookID, req.body.MemberID, req.body.BorrowDate], res));
app.delete('/borrows/:id', (req, res) => handleQuery('DELETE FROM Borrow WHERE BorrowID = ?', [req.params.id], res));

app.get('/returns', (req, res) => handleQuery('SELECT * FROM ReturnRecord', [], res));
app.post('/returns', (req, res) => handleQuery('INSERT INTO ReturnRecord (BorrowID, ReturnDate) VALUES (?, ?)', [req.body.BorrowID, req.body.ReturnDate], res));
app.delete('/returns/:id', (req, res) => handleQuery('DELETE FROM ReturnRecord WHERE ReturnID = ?', [req.params.id], res));

app.listen(5000, () => console.log('🚀 Server running on port 5000'));