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

namespace Indotalent.Features.Purchase.PurchaseReturn.Cqrs;

public class CreatePurchaseReturnItemRequest
{
    public string? PurchaseReturnId { get; set; }
    public string? WarehouseId { get; set; }
    public string? ProductId { get; set; }
    public double? Movement { get; set; }
}

public record CreatePurchaseReturnItemCommand(CreatePurchaseReturnItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreatePurchaseReturnItemCommand request, CancellationToken cancellationToken)
    {
        var parent = await _context.PurchaseReturn
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Data.PurchaseReturnId, 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.PurchaseReturn),
            ModuleCode = "PRN",
            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;
    }
}