export const dynamic = "force-dynamic";
import getDb from '@/lib/db';
import { getUserFromRequest, unauthorizedResponse, forbiddenResponse, checkRole } from '@/lib/auth';
import bcrypt from 'bcryptjs';

// GET /api/users - 获取所有用户列表（仅管理员）
export async function GET(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const db = await getDb();
    const users = db.prepare(`
      SELECT u.id, u.username, u.real_name, u.role, u.department_id, u.status, u.created_at,
             d.name as department_name
      FROM users u
      LEFT JOIN departments d ON u.department_id = d.id
      ORDER BY u.id ASC
    `).all();

    return Response.json(users);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// POST /api/users - 创建用户（仅管理员）
export async function POST(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['admin'])) return forbiddenResponse();

    const { username, password, real_name, role, department_id } = await request.json();

    if (!username || !password || !real_name || !role) {
      return Response.json(
        { error: '用户名、密码、姓名和角色不能为空' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 检查用户名是否重复
    const existing = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
    if (existing) {
      return Response.json(
        { error: '用户名已存在' },
        { status: 400 }
      );
    }

    // 加密密码
    const salt = bcrypt.genSaltSync(10);
    const hashedPassword = bcrypt.hashSync(password, salt);

    const result = db.prepare(
      'INSERT INTO users (username, password, real_name, role, department_id) VALUES (?, ?, ?, ?, ?)'
    ).run(username, hashedPassword, real_name, role, department_id || null);

    const newUser = db.prepare(
      `SELECT u.id, u.username, u.real_name, u.role, u.department_id, u.status, u.created_at,
              d.name as department_name
       FROM users u
       LEFT JOIN departments d ON u.department_id = d.id
       WHERE u.id = ?`
    ).get(result.lastInsertRowid);

    return Response.json(newUser, { status: 201 });
  } catch (error) {
    console.error('创建用户失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
