using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using LittleShop.DTOs;
using LittleShop.Services;

namespace LittleShop.Controllers;

[ApiController]
[Route("api/[controller]")]
public class CatalogController : ControllerBase
{
    private readonly ICategoryService _categoryService;
    private readonly IProductService _productService;

    public CatalogController(ICategoryService categoryService, IProductService productService)
    {
        _categoryService = categoryService;
        _productService = productService;
    }

    [HttpGet("categories")]
    public async Task<ActionResult<IEnumerable<CategoryDto>>> GetCategories()
    {
        var categories = await _categoryService.GetAllCategoriesAsync();
        return Ok(categories.Where(c => c.IsActive));
    }

    [HttpGet("categories/{id}")]
    public async Task<ActionResult<CategoryDto>> GetCategory(Guid id)
    {
        var category = await _categoryService.GetCategoryByIdAsync(id);
        if (category == null || !category.IsActive)
        {
            return NotFound();
        }

        return Ok(category);
    }

    [HttpGet("products")]
    public async Task<ActionResult<PagedResult<ProductDto>>> GetProducts(
        [FromQuery] int pageNumber = 1, 
        [FromQuery] int pageSize = 20, 
        [FromQuery] Guid? categoryId = null)
    {
        var allProducts = categoryId.HasValue 
            ? await _productService.GetProductsByCategoryAsync(categoryId.Value)
            : await _productService.GetAllProductsAsync();
            
        var productList = allProducts.ToList();
        var totalCount = productList.Count;
        var skip = (pageNumber - 1) * pageSize;
        var pagedProducts = productList.Skip(skip).Take(pageSize).ToList();
        
        var result = new PagedResult<ProductDto>
        {
            Items = pagedProducts,
            TotalCount = totalCount,
            PageNumber = pageNumber,
            PageSize = pageSize
        };
            
        return Ok(result);
    }

    [HttpGet("products/{id}")]
    public async Task<ActionResult<ProductDto>> GetProduct(Guid id)
    {
        var product = await _productService.GetProductByIdAsync(id);
        if (product == null || !product.IsActive)
        {
            return NotFound();
        }

        return Ok(product);
    }
}