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 DevicesController : ControllerBase
{
    private readonly IDeviceService _deviceService;

    public DevicesController(IDeviceService deviceService)
    {
        _deviceService = deviceService;
    }

    /// <summary>
    /// 获取当前用户的所有设备
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<List<DeviceDto>>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<List<DeviceDto>>>> GetDevices()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<List<DeviceDto>>.Fail("无效的用户"));
        }

        var devices = await _deviceService.GetUserDevicesAsync(userId.Value);

        return Ok(ApiResponse<List<DeviceDto>>.Ok(devices));
    }

    /// <summary>
    /// 获取设备详情
    /// </summary>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse<DeviceDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<DeviceDto>>> GetDevice(Guid id)
    {
        var device = await _deviceService.GetDeviceAsync(id);

        if (device == null)
        {
            return NotFound(ApiResponse<DeviceDto>.Fail("设备不存在"));
        }

        return Ok(ApiResponse<DeviceDto>.Ok(device));
    }

    /// <summary>
    /// 更新设备名称
    /// </summary>
    [HttpPut("{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse<DeviceDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<DeviceDto>>> UpdateDevice(Guid id, [FromBody] UpdateDeviceRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<DeviceDto>.Fail("无效的用户"));
        }

        var device = await _deviceService.UpdateDeviceNameAsync(id, userId.Value, request.DeviceName);

        if (device == null)
        {
            return NotFound(ApiResponse<DeviceDto>.Fail("设备不存在"));
        }

        return Ok(ApiResponse<DeviceDto>.Ok(device));
    }

    /// <summary>
    /// 删除设备
    /// </summary>
    [HttpDelete("{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse>> DeleteDevice(Guid id)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse.Fail("无效的用户"));
        }

        var success = await _deviceService.DeleteDeviceAsync(id, userId.Value);

        if (!success)
        {
            return BadRequest(ApiResponse.Fail("无法删除设备，可能是管理员设备或设备不存在"));
        }

        return Ok(ApiResponse.Ok("设备已删除"));
    }

    /// <summary>
    /// 设置管理员设备
    /// </summary>
    [HttpPut("{id:guid}/admin")]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse>> SetAdminDevice(Guid id)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse.Fail("无效的用户"));
        }

        var success = await _deviceService.SetAdminDeviceAsync(id, userId.Value);

        if (!success)
        {
            return BadRequest(ApiResponse.Fail("设置失败，设备不存在"));
        }

        return Ok(ApiResponse.Ok("已设置为管理员设备"));
    }

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

/// <summary>
/// 更新设备请求
/// </summary>
public class UpdateDeviceRequest
{
    /// <summary>
    /// 设备名称
    /// </summary>
    public string DeviceName { get; set; } = string.Empty;
}

