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

// GET /api/permissions - 获取所有角色权限（仅管理员）
export async function GET(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['admin'])) return forbiddenResponse();

    const db = await getDb();
    const permissions = db.prepare(
      'SELECT * FROM role_permissions ORDER BY role, menu_key'
    ).all();

    return Response.json(permissions);
  } catch (error) {
    console.error('获取权限配置失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// PUT /api/permissions - 更新角色权限（仅管理员）
export async function PUT(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['admin'])) return forbiddenResponse();

    let body = await request.json();

    if (!Array.isArray(body)) {
      if (body && Array.isArray(body.permissions)) {
        body = body.permissions;
      } else {
        return Response.json(
          { error: '请提供权限配置数组' },
          { status: 400 }
        );
      }
    }

    const db = await getDb();

    const upsertStmt = db.prepare(`
      INSERT INTO role_permissions (role, menu_key, visible)
      VALUES (?, ?, ?)
      ON CONFLICT(role, menu_key)
      DO UPDATE SET visible = excluded.visible
    `);

    const updateMany = db.transaction(() => {
      for (const item of body) {
        if (item.role && item.menu_key !== undefined && item.visible !== undefined) {
          upsertStmt.run(item.role, item.menu_key, item.visible ? 1 : 0);
        }
      }
    });
    updateMany();

    // 返回更新后的权限
    const permissions = db.prepare(
      'SELECT * FROM role_permissions ORDER BY role, menu_key'
    ).all();

    return Response.json(permissions);
  } catch (error) {
    console.error('更新权限配置失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
