using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Inventory.StockCount.Cqrs;

public class StockCountItemResponse
{
    public string? Id { get; set; }
    public string? ProductId { get; set; }
    public string? ProductName { get; set; }
    public double? QtySCSys { get; set; }
    public double? QtySCCount { get; set; }
    public double? QtySCDelta { get; set; }
}

public class GetStockCountByIdResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? CountDate { get; set; }
    public Data.Enums.StockCountStatus Status { get; set; }
    public string? Description { get; set; }
    public string? WarehouseId { get; set; }
    public string? WarehouseName { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
    public List<StockCountItemResponse> Items { get; set; } = new();
}

public record GetStockCountByIdQuery(string Id) : IRequest<GetStockCountByIdResponse?>;

public class GetStockCountByIdHandler : IRequestHandler<GetStockCountByIdQuery, GetStockCountByIdResponse?>
{
    private readonly AppDbContext _context;
    public GetStockCountByIdHandler(AppDbContext context) => _context = context;

    public async Task<GetStockCountByIdResponse?> Handle(GetStockCountByIdQuery request, CancellationToken cancellationToken)
    {
        var master = await _context.StockCount
            .AsNoTracking()
            .Include(x => x.Warehouse)
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

        if (master == null) return null;

        var items = await _context.InventoryTransaction
            .AsNoTracking()
            .Include(x => x.Product)
            .Where(x => x.ModuleId == request.Id && x.ModuleName == nameof(Data.Entities.StockCount))
            .Select(x => new StockCountItemResponse
            {
                Id = x.Id,
                ProductId = x.ProductId,
                ProductName = x.Product!.Name,
                QtySCSys = x.QtySCSys,
                QtySCCount = x.QtySCCount,
                QtySCDelta = x.QtySCDelta
            }).ToListAsync(cancellationToken);

        return new GetStockCountByIdResponse
        {
            Id = master.Id,
            AutoNumber = master.AutoNumber,
            CountDate = master.CountDate,
            Status = master.Status,
            Description = master.Description,
            WarehouseId = master.WarehouseId,
            WarehouseName = master.Warehouse?.Name,
            CreatedAt = master.CreatedAt,
            CreatedBy = master.CreatedBy,
            UpdatedAt = master.UpdatedAt,
            UpdatedBy = master.UpdatedBy,
            Items = items
        };
    }
}