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

namespace Indotalent.Features.Purchase.GoodsReceive.Cqrs;

public class CreateGoodsReceiveRequest
{
    public DateTime? ReceiveDate { get; set; }
    public Data.Enums.GoodsReceiveStatus Status { get; set; }
    public string? Description { get; set; }
    public string? PurchaseOrderId { get; set; }
}

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

public record CreateGoodsReceiveCommand(CreateGoodsReceiveRequest Data) : IRequest<CreateGoodsReceiveResponse>;

public class CreateGoodsReceiveHandler : IRequestHandler<CreateGoodsReceiveCommand, CreateGoodsReceiveResponse>
{
    private readonly AppDbContext _context;
    public CreateGoodsReceiveHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.GoodsReceive
        {
            AutoNumber = autoNo,
            ReceiveDate = request.Data.ReceiveDate,
            Status = request.Data.Status,
            Description = request.Data.Description,
            PurchaseOrderId = request.Data.PurchaseOrderId
        };

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

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