using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiGu.Server.Configs;

namespace MiGu.Server.Controllers;

// AR-4: 全 class 加 [Authorize] —— 替代会话21 点名的「ConfigController 无鉴权 PUT 任意 section」漏洞。
// GET (List/Get) 只要登录就放；PUT 强制 PlatformScope，避免运营人员误改业务配置。
[ApiController]
[Authorize]
[Route("api/config")]
public class ConfigController : ControllerBase
{
    private readonly ConfigStore _store;

    public ConfigController(ConfigStore store)
    {
        _store = store;
    }

    [HttpGet]
    public IActionResult List()
    {
        var envs = _store.List().Select(e => new
        {
            section = e.Section,
            version = e.Version,
            updatedAt = e.UpdatedAt
        });
        return Ok(envs);
    }

    [HttpGet("{section}")]
    public IActionResult Get(string section)
    {
        if (!ConfigStore.AllSections.Contains(section, StringComparer.OrdinalIgnoreCase))
            return NotFound(new { message = $"未知 section: {section}" });

        var env = _store.Get(section);
        return Ok(new
        {
            section = env.Section,
            version = env.Version,
            updatedAt = env.UpdatedAt,
            payload = env.Payload
        });
    }

    // 配置中心页面已有 PermissionGuard；此处仅要求登录即可保存，避免 RCSMonitor scope
    // 账号在特殊场景下无法写入 ops.monitor（地图监控动作）备份字段。
    [HttpPut("{section}")]
    [Authorize]
    public IActionResult Put(string section, [FromBody] JsonElement payload)
    {
        if (!ConfigStore.AllSections.Contains(section, StringComparer.OrdinalIgnoreCase))
            return NotFound(new { message = $"未知 section: {section}" });

        var env = _store.Put(section, payload);
        return Ok(new
        {
            section = env.Section,
            version = env.Version,
            updatedAt = env.UpdatedAt,
            payload = env.Payload
        });
    }
}
