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

// GET /api/auth/me - 获取当前登录用户信息
export async function GET(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) {
      return unauthorizedResponse();
    }

    const db = await getDb();

    // 获取完整用户信息
    const fullUser = db.prepare(
      'SELECT id, username, real_name, role, department_id, status, created_at FROM users WHERE id = ?'
    ).get(user.id);

    if (!fullUser || fullUser.status !== 1) {
      return unauthorizedResponse();
    }

    // 获取部门名称
    if (fullUser.department_id) {
      const dept = db.prepare('SELECT name FROM departments WHERE id = ?').get(fullUser.department_id);
      if (dept) {
        fullUser.department_name = dept.name;
      }
    }

    // 获取角色权限
    const permissions = db.prepare(
      'SELECT menu_key, visible FROM role_permissions WHERE role = ?'
    ).all(fullUser.role);

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