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

namespace Indotalent.Features.Purchase.PurchaseReturn.Cqrs;

public class CreatePurchaseReturnRequest
{
    public DateTime? ReturnDate { get; set; }
    public Data.Enums.PurchaseReturnStatus Status { get; set; }
    public string? Description { get; set; }
    public string? GoodsReceiveId { get; set; }
}

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

public record CreatePurchaseReturnCommand(CreatePurchaseReturnRequest Data) : IRequest<CreatePurchaseReturnResponse>;

public class CreatePurchaseReturnHandler : IRequestHandler<CreatePurchaseReturnCommand, CreatePurchaseReturnResponse>
{
    private readonly AppDbContext _context;
    public CreatePurchaseReturnHandler(AppDbContext context) => _context = context;

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

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

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

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