using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiGu.Server.Dashboard;

namespace MiGu.Server.Controllers;

[ApiController]
[Authorize]
[Route("api/dashboard")]
public class DashboardController : ControllerBase
{
    private readonly DashboardShortcutService _shortcuts;

    public DashboardController(DashboardShortcutService shortcuts) => _shortcuts = shortcuts;

    public sealed record SaveQuickEntriesRequest(List<string>? Keys);

    [HttpGet("quick-entries")]
    public async Task<IActionResult> GetQuickEntries(CancellationToken ct)
    {
        var (userId, scope, err) = ResolveSession();
        if (err != null) return err;

        var result = await _shortcuts.GetAsync(userId!, scope!, ct);
        return Ok(new { keys = result.Keys, usingDefaults = result.UsingDefaults });
    }

    [HttpPut("quick-entries")]
    public async Task<IActionResult> SaveQuickEntries(
        [FromBody] SaveQuickEntriesRequest req, CancellationToken ct)
    {
        var (userId, scope, err) = ResolveSession();
        if (err != null) return err;

        var result = await _shortcuts.SaveAsync(userId!, scope!, req.Keys, ct);
        return Ok(new { keys = result.Keys, usingDefaults = result.UsingDefaults });
    }

    private (string? UserId, string? Scope, IActionResult? Error) ResolveSession()
    {
        var userId = User.FindFirstValue(JwtRegisteredClaimNames.Sub)
            ?? User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrWhiteSpace(userId))
            return (null, null, Unauthorized(new { message = "未识别用户" }));

        var scope = User.FindFirstValue("scope");
        if (string.IsNullOrWhiteSpace(scope))
            return (null, null, BadRequest(new { message = "会话缺少 scope" }));

        return (userId, scope, null);
    }
}
