using Bimix.Application.DTOModels;
using Bimix.Application.DTOModels.Common;
using Microsoft.AspNetCore.Mvc;
using Bimix.Infrastructure.Data;
using Bimix.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace Bimix.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ProductsController(BimixDbContext context) : ControllerBase
{
    private readonly BimixDbContext _context = context;
    
    [HttpGet]
    public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts([FromQuery] ProductFilterRequest request)
    {
        var query = _context.Products.AsQueryable();

        if (!string.IsNullOrWhiteSpace(request.Search))
        {
            var searchTerm = request.Search.ToLower();
            query = query.Where(x => 
                x.Name.ToLower().Contains(searchTerm) ||
                (x.Code != null && x.Code.ToLower().Contains(searchTerm)) ||
                (x.Ean != null && x.Ean.ToLower().Contains(searchTerm))
                );
        }

        if (!string.IsNullOrWhiteSpace(request.Name))
        {
            query = query.Where(x => x.Name.ToLower().Contains(request.Name.ToLower()));
        }

        if (!string.IsNullOrWhiteSpace(request.Code))
        {
            query = query.Where(x => x.Code != null && x.Code.ToLower().Contains(request.Code.ToLower()));
        }

        if (!string.IsNullOrWhiteSpace(request.Ean))
        {
            query = query.Where(x => x.Ean != null && x.Ean.ToLower().Contains(request.Ean.ToLower()));
        }

        var totalCount = await query.CountAsync();
        
        var items = await query
            .OrderBy(x => x.Name)
            .Skip((request.Page -1) * request.PageSize)
            .Take(request.PageSize)
            .Select(x => new ProductDto
            {
                Id = x.Id,
                Name = x.Name,
                Code = x.Code ?? string.Empty,
                Ean = x.Ean ?? string.Empty,
                StockAddresses = x.StockAddresses ?? string.Empty,
                CreatedAt = x.CreatedAt,
                UpdatedAt = x.UpdatedAt
            })
            .ToListAsync();

        return Ok(new PagedResult<ProductDto>
        {
            Items = items,
            TotalCount = totalCount,
            Page = request.Page,
            PageSize = request.PageSize,
        });
    }
}