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

namespace Indotalent.Features.Purchase.GoodsReceive.Cqrs;

public class CreateGoodsReceiveItemRequest
{
    public string? GoodsReceiveId { get; set; }
    public string? WarehouseId { get; set; }
    public string? ProductId { get; set; }
    public double? Movement { get; set; }
}

public record CreateGoodsReceiveItemCommand(CreateGoodsReceiveItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreateGoodsReceiveItemCommand request, CancellationToken cancellationToken)
    {
        var parent = await _context.GoodsReceive
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Data.GoodsReceiveId, 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.GoodsReceive),
            ModuleCode = "GR",
            ModuleNumber = parent.AutoNumber,
            MovementDate = parent.ReceiveDate ?? 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;
    }
}