const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3000;
const USERS_FILE = path.join(__dirname, 'user.json');

// 初始化user.json文件
if (!fs.existsSync(USERS_FILE)) {
    fs.writeFileSync(USERS_FILE, JSON.stringify([]));
}

app.use(bodyParser.json());

// 接口文档路由
app.get('/', (req, res) => {
    const apiDocs = {
        description: '用户服务API文档',
        endpoints: [
            {
                path: '/signup',
                method: 'POST',
                description: '用户注册',
                requestBody: {
                    username: 'string',
                    password: 'string'
                }
            },
            {
                path: '/login',
                method: 'POST',
                description: '用户登录',
                requestBody: {
                    username: 'string',
                    password: 'string'
                }
            }
        ]
    };
    res.json(apiDocs);
});

// 用户注册路由
app.post('/signup', (req, res) => {
    const { username, password } = req.body;
    
    if (!username || !password) {
        return res.status(400).json({ error: '用户名和密码不能为空' });
    }

    const users = JSON.parse(fs.readFileSync(USERS_FILE));
    const userExists = users.some(user => user.username === username);

    if (userExists) {
        return res.status(400).json({ error: '用户名已存在' });
    }

    users.push({ username, password });
    fs.writeFileSync(USERS_FILE, JSON.stringify(users));
    
    res.status(201).json({ message: '注册成功' });
});

// 用户登录路由
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    
    if (!username || !password) {
        return res.status(400).json({ error: '用户名和密码不能为空' });
    }

    const users = JSON.parse(fs.readFileSync(USERS_FILE));
    const user = users.find(user => user.username === username);

    if (!user) {
        return res.status(401).json({ error: '用户名不存在' });
    }

    if (user.password !== password) {
        return res.status(401).json({ error: '密码错误' });
    }

    res.json({ message: '登录成功' });
});

app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});