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

namespace Indotalent.Features.Inventory.TransferIn.Cqrs;

public class CreateTransferInRequest
{
    public DateTime? TransferReceiveDate { get; set; }
    public Data.Enums.TransferStatus Status { get; set; }
    public string? Description { get; set; }
    public string? TransferOutId { get; set; }
}

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

public record CreateTransferInCommand(CreateTransferInRequest Data) : IRequest<CreateTransferInResponse>;

public class CreateTransferInHandler : IRequestHandler<CreateTransferInCommand, CreateTransferInResponse>
{
    private readonly AppDbContext _context;
    public CreateTransferInHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.TransferIn
        {
            AutoNumber = autoNo,
            TransferReceiveDate = request.Data.TransferReceiveDate,
            Status = request.Data.Status,
            Description = request.Data.Description,
            TransferOutId = request.Data.TransferOutId
        };

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

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