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

namespace Indotalent.Features.Sales.SalesReturn.Cqrs;

public class UpdateSalesReturnRequest
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
    public DateTime? ReturnDate { get; set; }
    public Data.Enums.SalesReturnStatus Status { get; set; }
    public string? Description { get; set; }
    public string? DeliveryOrderId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateSalesReturnCommand(UpdateSalesReturnRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.ReturnDate = request.Data.ReturnDate;
        entity.Status = request.Data.Status;
        entity.Description = request.Data.Description;
        entity.DeliveryOrderId = request.Data.DeliveryOrderId;

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

        foreach (var trans in transactions)
        {
            trans.MovementDate = entity.ReturnDate ?? DateTime.Now;
            trans.ModuleNumber = entity.AutoNumber;
            trans.Status = (Data.Enums.InventoryTransactionStatus)entity.Status;
            _context.CalculateInvenTrans(trans);
        }

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