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

namespace Indotalent.Features.Inventory.Scrapping.Cqrs;

public class CreateScrappingRequest
{
    public DateTime? ScrappingDate { get; set; }
    public Data.Enums.ScrappingStatus Status { get; set; }
    public string? Description { get; set; }
    public string? WarehouseId { get; set; }
}

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

public record CreateScrappingCommand(CreateScrappingRequest Data) : IRequest<CreateScrappingResponse>;

public class CreateScrappingHandler : IRequestHandler<CreateScrappingCommand, CreateScrappingResponse>
{
    private readonly AppDbContext _context;
    public CreateScrappingHandler(AppDbContext context) => _context = context;

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

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

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

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