const fs = require('fs');
const path = require('path');
const userDataPath = path.join(__dirname, 'data', 'user.json');

// 读取用户数据
const readUserData = () => {
    return JSON.parse(fs.readFileSync(userDataPath, 'utf-8') || '[]');
};

// 写入用户数据
const writeUserData = (data) => {
    fs.writeFileSync(userDataPath, JSON.stringify(data, null, 2));
};

// 注册用户
const registerUser = (username, password, confirmPassword) => {
    const users = readUserData();

    if (!username || !password || password !== confirmPassword) {
        throw new Error('无效的输入');
    }

    if (users.find(user => user.username === username)) {
        throw new Error('用户已存在');
    }

    users.push({ username, password,img:"https://oy-bucket.obs.cn-south-1.myhuaweicloud.com/img//202409241719043.jpeg" });
    writeUserData(users);
};

// 登录用户
const loginUser = (username, password) => {
    const users = readUserData();
    const user = users.find(user => user.username === username && user.password === password);

    if (!user) {
        throw new Error('用户名或密码错误');
    }

    return user; // 返回用户信息（可选）
};

module.exports = {
    registerUser,
    loginUser
};
