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

// GET /api/config - 获取系统配置（公开，无需认证）
export async function GET() {
  try {
    const db = await getDb();
    const configs = db.prepare('SELECT config_key, config_value FROM system_config').all();
    const result = {};
    for (const config of configs) {
      result[config.config_key] = config.config_value;
    }
    return Response.json(result);
  } catch (error) {
    console.error('获取系统配置失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// PUT /api/config - 更新系统配置（仅管理员）
export async function PUT(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['admin'])) return forbiddenResponse();

    const body = await request.json();
    const db = await getDb();

    const updateStmt = db.prepare(
      'UPDATE system_config SET config_value = ?, updated_at = CURRENT_TIMESTAMP WHERE config_key = ?'
    );

    const allowedKeys = ['company_name', 'company_logo', 'profit_percentage'];

    const updateMany = db.transaction(() => {
      for (const key of allowedKeys) {
        if (body[key] !== undefined) {
          updateStmt.run(String(body[key]), key);
        }
      }
    });
    updateMany();

    // 返回更新后的配置
    const configs = db.prepare('SELECT config_key, config_value FROM system_config').all();
    const result = {};
    for (const config of configs) {
      result[config.config_key] = config.config_value;
    }
    return Response.json(result);
  } catch (error) {
    console.error('更新系统配置失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
