using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Meezi.API.Models.Consumer;
using Meezi.API.Services;
using Meezi.Core.Constants;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[ApiController]
[Authorize]
[Route("api/customers/me")]
public class CustomerMeController : ControllerBase
{
    private readonly IConsumerOrdersService _orders;

    public CustomerMeController(IConsumerOrdersService orders) => _orders = orders;

    [HttpGet("orders")]
    public async Task<IActionResult> GetOrders(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        CancellationToken ct = default)
    {
        if (User.FindFirst(MeeziClaimTypes.Actor)?.Value != MeeziActorKinds.Consumer)
            return Forbid();

        var phone = User.FindFirst(MeeziClaimTypes.Phone)?.Value;
        if (string.IsNullOrEmpty(phone))
            return Unauthorized(new ApiResponse<object>(false, null, new ApiError("UNAUTHORIZED", "Phone claim missing.")));

        var data = await _orders.GetMyOrdersAsync(phone, page, pageSize, ct);
        return Ok(new ApiResponse<IReadOnlyList<ConsumerOrderHistoryDto>>(true, data));
    }
}
