// EN: Categories REST API Controller.
// VI: Controller REST API cho Categories.

using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using CatalogService.API.Application.Commands;
using CatalogService.API.Application.DTOs;
using CatalogService.API.Application.Queries;

namespace CatalogService.API.Controllers;

/// <summary>
/// EN: Categories API Controller.
/// VI: Controller API Categories.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/categories")]
public class CategoriesController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<CategoriesController> _logger;

    public CategoriesController(
        IMediator mediator,
        ILogger<CategoriesController> logger)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Get categories by shop with hierarchical support.
    /// VI: Lấy danh mục theo shop có hỗ trợ phân cấp.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(List<CategoryDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<CategoryDto>>> GetCategories(
        [FromQuery] Guid shopId,
        [FromQuery] Guid? parentId = null,
        CancellationToken cancellationToken = default)
    {
        var query = new GetCategoriesQuery
        {
            ShopId = shopId,
            ParentId = parentId
        };

        var result = await _mediator.Send(query, cancellationToken);
        return Ok(result);
    }

    /// <summary>
    /// EN: Create a new category.
    /// VI: Tạo danh mục mới.
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(Guid), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<Guid>> CreateCategory(
        [FromBody] CreateCategoryCommand command,
        CancellationToken cancellationToken = default)
    {
        var categoryId = await _mediator.Send(command, cancellationToken);
        return CreatedAtAction(
            nameof(GetCategories),
            new { shopId = command.ShopId },
            categoryId);
    }
}
