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

namespace Indotalent.Features.Sales.SalesReturn.Cqrs;

public class CreateSalesReturnItemRequest
{
    public string? SalesReturnId { get; set; }
    public string? WarehouseId { get; set; }
    public string? ProductId { get; set; }
    public double? Movement { get; set; }
}

public record CreateSalesReturnItemCommand(CreateSalesReturnItemRequest Data) : IRequest<bool>;

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

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

        if (parent == null) return false;

        var ivtEntityName = nameof(Data.Entities.InventoryTransaction);
        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: ivtEntityName,
            prefixTemplate: $"{ivtEntityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.InventoryTransaction
        {
            AutoNumber = autoNo,
            ModuleId = parent.Id,
            ModuleName = nameof(Data.Entities.SalesReturn),
            ModuleCode = "SRN",
            ModuleNumber = parent.AutoNumber,
            MovementDate = parent.ReturnDate ?? DateTime.Now,
            Status = (Data.Enums.InventoryTransactionStatus)parent.Status,
            WarehouseId = request.Data.WarehouseId,
            ProductId = request.Data.ProductId,
            Movement = request.Data.Movement
        };

        _context.CalculateInvenTrans(entity);
        _context.InventoryTransaction.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}