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

namespace Indotalent.Features.Inventory.TransferOut.Cqrs;

public class CreateTransferOutRequest
{
    public DateTime? TransferReleaseDate { get; set; }
    public Data.Enums.TransferStatus Status { get; set; }
    public string? Description { get; set; }
    public string? WarehouseFromId { get; set; }
    public string? WarehouseToId { get; set; }
}

public class CreateTransferOutResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
}

public record CreateTransferOutCommand(CreateTransferOutRequest Data) : IRequest<CreateTransferOutResponse>;

public class CreateTransferOutHandler : IRequestHandler<CreateTransferOutCommand, CreateTransferOutResponse>
{
    private readonly AppDbContext _context;
    public CreateTransferOutHandler(AppDbContext context) => _context = context;

    public async Task<CreateTransferOutResponse> Handle(CreateTransferOutCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.TransferOut);
        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.TransferOut
        {
            AutoNumber = autoNo,
            TransferReleaseDate = request.Data.TransferReleaseDate,
            Status = request.Data.Status,
            Description = request.Data.Description,
            WarehouseFromId = request.Data.WarehouseFromId,
            WarehouseToId = request.Data.WarehouseToId
        };

        _context.TransferOut.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreateTransferOutResponse
        {
            Id = entity.Id,
            AutoNumber = entity.AutoNumber
        };
    }
}