using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MissionService.API.Application.Commands;
using MissionService.API.Application.Queries;

namespace MissionService.API.Controllers;

/// <summary>
/// EN: Controller for mission operations
/// VI: Controller cho các thao tác mission
/// </summary>
[ApiController]
[Route("api/v1/[controller]")]
[Authorize]
public class MissionsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<MissionsController> _logger;

    public MissionsController(IMediator mediator, ILogger<MissionsController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// EN: Get all available missions / VI: Lấy tất cả missions khả dụng
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(MissionsListResult), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetAvailableMissions()
    {
        var userId = GetCurrentUserId();
        var result = await _mediator.Send(new GetAvailableMissionsQuery(userId));
        return Ok(result);
    }

    /// <summary>
    /// EN: Get missions by category / VI: Lấy missions theo danh mục
    /// </summary>
    [HttpGet("category/{category}")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(MissionsListResult), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetByCategory(string category)
    {
        var result = await _mediator.Send(new GetMissionsByCategoryQuery(category));
        return Ok(result);
    }

    /// <summary>
    /// EN: Get mission details / VI: Lấy chi tiết mission
    /// </summary>
    [HttpGet("{id:guid}")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(MissionDetailsResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetDetails(Guid id)
    {
        var userId = TryGetCurrentUserId();
        var result = await _mediator.Send(new GetMissionDetailsQuery(id, userId));
        
        if (result == null)
        {
            return NotFound(new { Message = "Mission not found / Không tìm thấy mission" });
        }

        return Ok(result);
    }

    /// <summary>
    /// EN: Start a mission task / VI: Bắt đầu task mission
    /// </summary>
    [HttpPost("{id:guid}/start")]
    [ProducesResponseType(typeof(StartTaskResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> StartMission(Guid id)
    {
        var userId = GetCurrentUserId();
        var result = await _mediator.Send(new StartMissionTaskCommand(userId, id));
        
        if (!result.Success)
        {
            return BadRequest(result);
        }

        return Ok(result);
    }

    /// <summary>
    /// EN: Update task progress / VI: Cập nhật tiến độ task
    /// </summary>
    [HttpPut("tasks/{taskId:guid}/progress")]
    [ProducesResponseType(typeof(UpdateProgressResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> UpdateProgress(Guid taskId, [FromBody] UpdateProgressRequest request)
    {
        var userId = GetCurrentUserId();
        var result = await _mediator.Send(new UpdateTaskProgressCommand(
            userId, 
            taskId, 
            request.CurrentValue,
            request.Evidence));
        
        if (!result.Success)
        {
            return BadRequest(result);
        }

        return Ok(result);
    }

    /// <summary>
    /// EN: Claim task reward / VI: Nhận thưởng task
    /// </summary>
    [HttpPost("tasks/{taskId:guid}/claim")]
    [ProducesResponseType(typeof(ClaimRewardResult), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> ClaimReward(Guid taskId)
    {
        var userId = GetCurrentUserId();
        var result = await _mediator.Send(new ClaimTaskRewardCommand(userId, taskId));
        
        if (!result.Success)
        {
            return BadRequest(result);
        }

        return Ok(result);
    }

    private Guid GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst("sub") ?? User.FindFirst("user_id");
        if (userIdClaim != null && Guid.TryParse(userIdClaim.Value, out var userId))
        {
            return userId;
        }
        throw new UnauthorizedAccessException("User ID not found in token");
    }

    private Guid? TryGetCurrentUserId()
    {
        var userIdClaim = User.FindFirst("sub") ?? User.FindFirst("user_id");
        if (userIdClaim != null && Guid.TryParse(userIdClaim.Value, out var userId))
        {
            return userId;
        }
        return null;
    }
}

/// <summary>
/// EN: Request to update progress / VI: Request cập nhật tiến độ
/// </summary>
public record UpdateProgressRequest(int CurrentValue, TaskEvidenceDto? Evidence = null);
