using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using BookmarkApi.Core.Interfaces;
using BookmarkApi.Shared.DTOs;

namespace BookmarkApi.Controllers;

/// <summary>
/// 标签控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class TagsController : ControllerBase
{
    private readonly ITagService _tagService;
    private readonly IDeviceService _deviceService;

    public TagsController(ITagService tagService, IDeviceService deviceService)
    {
        _tagService = tagService;
        _deviceService = deviceService;
    }

    /// <summary>
    /// 获取标签列表
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<List<TagDto>>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<List<TagDto>>>> GetTags()
    {
        var (userId, deviceId, isAdmin) = await GetCurrentContext();
        if (userId == null || deviceId == null)
        {
            return BadRequest(ApiResponse<List<TagDto>>.Fail("无效的用户或设备"));
        }

        var tags = await _tagService.GetUserTagsAsync(userId.Value, deviceId.Value, isAdmin);

        return Ok(ApiResponse<List<TagDto>>.Ok(tags));
    }

    /// <summary>
    /// 重命名标签
    /// </summary>
    [HttpPut("{name}")]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse>> RenameTag(string name, [FromBody] RenameTagRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse.Fail("无效的用户"));
        }

        var success = await _tagService.RenameTagAsync(userId.Value, name, request.NewName);

        if (!success)
        {
            return NotFound(ApiResponse.Fail("标签不存在"));
        }

        return Ok(ApiResponse.Ok("标签已重命名"));
    }

    /// <summary>
    /// 删除标签
    /// </summary>
    [HttpDelete("{name}")]
    [ProducesResponseType(typeof(ApiResponse<int>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<int>>> DeleteTag(string name)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<int>.Fail("无效的用户"));
        }

        var count = await _tagService.DeleteTagAsync(userId.Value, name);

        return Ok(ApiResponse<int>.Ok(count, $"已从 {count} 个书签中移除该标签"));
    }

    /// <summary>
    /// 合并标签
    /// </summary>
    [HttpPost("merge")]
    [ProducesResponseType(typeof(ApiResponse<int>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<int>>> MergeTags([FromBody] MergeTagsRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<int>.Fail("无效的用户"));
        }

        var count = await _tagService.MergeTagsAsync(userId.Value, request.SourceNames, request.TargetName);

        return Ok(ApiResponse<int>.Ok(count, $"已合并 {count} 个书签的标签"));
    }

    private Guid? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        return Guid.TryParse(userIdClaim, out var userId) ? userId : null;
    }

    private Guid? GetCurrentDeviceId()
    {
        var deviceIdClaim = User.FindFirst("device_id")?.Value;
        return Guid.TryParse(deviceIdClaim, out var deviceId) ? deviceId : null;
    }

    private async Task<(Guid? userId, Guid? deviceId, bool isAdmin)> GetCurrentContext()
    {
        var userId = GetCurrentUserId();
        var deviceId = GetCurrentDeviceId();

        if (userId == null || deviceId == null)
        {
            return (null, null, false);
        }

        var isAdmin = await _deviceService.IsAdminDeviceAsync(deviceId.Value);

        return (userId, deviceId, isAdmin);
    }
}

/// <summary>
/// 重命名标签请求
/// </summary>
public class RenameTagRequest
{
    /// <summary>
    /// 新标签名称
    /// </summary>
    public string NewName { get; set; } = string.Empty;
}

/// <summary>
/// 合并标签请求
/// </summary>
public class MergeTagsRequest
{
    /// <summary>
    /// 源标签名称数组
    /// </summary>
    public string[] SourceNames { get; set; } = Array.Empty<string>();

    /// <summary>
    /// 目标标签名称
    /// </summary>
    public string TargetName { get; set; } = string.Empty;
}

