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

namespace Indotalent.Features.Inventory.StockCount.Cqrs;

public class UpdateStockCountRequest
{
    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 DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateStockCountCommand(UpdateStockCountRequest Data) : IRequest<bool>;

public class UpdateStockCountHandler : IRequestHandler<UpdateStockCountCommand, bool>
{
    private readonly AppDbContext _context;
    public UpdateStockCountHandler(AppDbContext context) => _context = context;

    public async Task<bool> Handle(UpdateStockCountCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.StockCount
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null) return false;

        entity.CountDate = request.Data.CountDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;
        entity.WarehouseId = request.Data.WarehouseId;

        var details = await _context.InventoryTransaction
            .Where(x => x.ModuleId == entity.Id && x.ModuleName == nameof(Data.Entities.StockCount))
            .ToListAsync(cancellationToken);

        foreach (var item in details)
        {
            item.MovementDate = entity.CountDate ?? DateTime.Now;
            item.Status = (Data.Enums.InventoryTransactionStatus)entity.Status;
            item.WarehouseId = entity.WarehouseId;
            item.ModuleNumber = entity.AutoNumber;
            _context.CalculateInvenTrans(item);
        }

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}