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

namespace Indotalent.Features.Sales.SalesReturn.Cqrs;

public class CreateSalesReturnRequest
{
    public DateTime? ReturnDate { get; set; }
    public Data.Enums.SalesReturnStatus Status { get; set; }
    public string? Description { get; set; }
    public string? DeliveryOrderId { get; set; }
}

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

public record CreateSalesReturnCommand(CreateSalesReturnRequest Data) : IRequest<CreateSalesReturnResponse>;

public class CreateSalesReturnHandler : IRequestHandler<CreateSalesReturnCommand, CreateSalesReturnResponse>
{
    private readonly AppDbContext _context;
    public CreateSalesReturnHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.SalesReturn
        {
            AutoNumber = autoNo,
            ReturnDate = request.Data.ReturnDate,
            Status = request.Data.Status,
            Description = request.Data.Description,
            DeliveryOrderId = request.Data.DeliveryOrderId
        };

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

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