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

namespace Indotalent.Features.Sales.DeliveryOrder.Cqrs;

public class CreateDeliveryOrderRequest
{
    public DateTime? DeliveryDate { get; set; }
    public Data.Enums.DeliveryOrderStatus Status { get; set; }
    public string? Description { get; set; }
    public string? SalesOrderId { get; set; }
}

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

public record CreateDeliveryOrderCommand(CreateDeliveryOrderRequest Data) : IRequest<CreateDeliveryOrderResponse>;

public class CreateDeliveryOrderHandler : IRequestHandler<CreateDeliveryOrderCommand, CreateDeliveryOrderResponse>
{
    private readonly AppDbContext _context;
    public CreateDeliveryOrderHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.DeliveryOrder
        {
            AutoNumber = autoNo,
            DeliveryDate = request.Data.DeliveryDate,
            Status = request.Data.Status,
            Description = request.Data.Description,
            SalesOrderId = request.Data.SalesOrderId
        };

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

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