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

namespace Indotalent.Features.Inventory.StockCount.Cqrs;

public class CreateStockCountRequest
{
    public DateTime? CountDate { get; set; }
    public Data.Enums.StockCountStatus Status { get; set; }
    public string? Description { get; set; }
    public string? WarehouseId { get; set; }
}

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

public record CreateStockCountCommand(CreateStockCountRequest Data) : IRequest<CreateStockCountResponse>;

public class CreateStockCountHandler : IRequestHandler<CreateStockCountCommand, CreateStockCountResponse>
{
    private readonly AppDbContext _context;
    public CreateStockCountHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.StockCount
        {
            AutoNumber = autoNo,
            CountDate = request.Data.CountDate,
            Status = request.Data.Status,
            Description = request.Data.Description,
            WarehouseId = request.Data.WarehouseId
        };

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

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