const express = require("express")
const mysql = require("mysql2")
const cors = require("cors")

const app = express()
const port = 3000

const db = mysql.createConnection({
    host: "127.0.0.1",
    port: 3306,
    user: "root",
    password: "123456",
    database: "express_db"
})

db.connect((err) => {
    if (err) {
        console.log("Error connect to MySQL database:", err);
        return;
    }
    console.log("Connected to MySQL database");
})

app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cors({
    origin: "http://127.0.0.1:3000",
    method: ["GET", "POST"],
    allowedHeaders: ['Content-Type', "Authorization"]
}))
app.use(express.static("public"))

app.options('/login', cors());

app.post('/register', (req, res) => {
    const { username, password, email, gender, hobbies, city, description } = req.body;
    const hobbiesStr = hobbies ? hobbies.join(",") : "";
    const sql = 'INSERT INTO users (username, password, email, gender, hobbies, city, description) VALUES (?,?,?,?,?,?,?)'
    const values = [username, password, email, gender, hobbiesStr, city, description]
    db.query(sql, values, (err, result) => {
        if (err) {
            console.error('Error inserting data into MySQL database:', err);
            res.status(500).send("Error inserting data into MySQL database");
            return;
        }
        console.log("inserting data successful!");
        res.send("Register successful")
    })
})

app.post("/login", (req, res) => {
    const { username, password } = req.body;
    const sql = 'SELECT * FROM users WHERE username = ? AND password = ?';
    const values = [username, password];

    db.query(sql, values, (err, result) => {
        if (err) {
            console.error("Error querying the database:", err);
            res.status(500).send("Error querying the database");
            return;
        }
        if (result.length > 0) {
            console.log('Login successful');
            res.send('Login successful');
        } else {
            console.log("Login failed");
            res.send("Login failed");
        }
    })
})

app.post("/update-password", (req, res) => {
    const { username, currentPassword, newPassword } = req.body;
    const sqlCheck = 'SELECT * FROM users WHERE username = ? AND password = ?';
    const checkValues = [username, currentPassword];
    db.query(sqlCheck, checkValues, (err, result) => {
        if (err) {
            console.error("Error querying the database:", err);
            res.status(500).send("Error querying the database");
            return;
        }
        if (result.length == 0) {
            console.log("当前密码输入错误");
            res.status(400).send("Current password is incorret");
            return;
        }
        const updateSql = "UPDATE users SET password = ? WHERE username = ?";
        const updateValue = [newPassword, username];

        db.query(updateSql, updateValue, (err2, result2) => {
            if (err2) {
                console.error("Error updating user password:", err2);
                res.status(500).send('Error updating user password');
                return;
            }
            console.log(result2);
            
            console.log("User password update successful");
            res.send("User password update successful")
        })
    })
})

app.listen(port, () => {
    console.log(`Server is running: http://127.0.0.1:${port}`);
})
