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/[id] - 获取单个用户信息
export async function GET(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { id } = await params;
    const db = await getDb();

    const targetUser = 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(id);

    if (!targetUser) {
      return Response.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

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

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

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

    const db = await getDb();

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

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

    // 构建更新字段
    const updates = [];
    const values = [];

    if (username !== undefined) { updates.push('username = ?'); values.push(username); }
    if (real_name !== undefined) { updates.push('real_name = ?'); values.push(real_name); }
    if (role !== undefined) { updates.push('role = ?'); values.push(role); }
    if (department_id !== undefined) { updates.push('department_id = ?'); values.push(department_id || null); }
    if (status !== undefined) { updates.push('status = ?'); values.push(status); }

    // 如果提供了密码，加密后更新
    if (password) {
      const salt = bcrypt.genSaltSync(10);
      const hashedPassword = bcrypt.hashSync(password, salt);
      updates.push('password = ?');
      values.push(hashedPassword);
    }

    if (updates.length === 0) {
      return Response.json(
        { error: '没有需要更新的字段' },
        { status: 400 }
      );
    }

    values.push(id);
    db.prepare(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`).run(...values);

    const updatedUser = 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(id);

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

// DELETE /api/users/[id] - 直接删除用户（仅管理员）
export async function DELETE(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['admin'])) return forbiddenResponse();

    const { id } = await params;
    const db = await getDb();

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

    // 不能删除自己
    if (Number(id) === user.id) {
      return Response.json(
        { error: '不能删除自己的账号' },
        { status: 400 }
      );
    }

    // 直接删除用户，不保留
    db.prepare('DELETE FROM users WHERE id = ?').run(id);

    return Response.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除用户失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
