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

namespace Indotalent.Features.Purchase.Bill.Cqrs;

public class CreateBillRequest
{
    public DateTime? BillDate { get; set; }
    public Data.Enums.BillStatus BillStatus { get; set; }
    public string? Description { get; set; }
    public string? PurchaseOrderId { get; set; }
}

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

public record CreateBillCommand(CreateBillRequest Data) : IRequest<CreateBillResponse>;

public class CreateBillHandler : IRequestHandler<CreateBillCommand, CreateBillResponse>
{
    private readonly AppDbContext _context;
    public CreateBillHandler(AppDbContext context) => _context = context;

    public async Task<CreateBillResponse> Handle(CreateBillCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.Bill);
        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"BILL/{{Year}}/{{Month}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.Bill
        {
            AutoNumber = autoNo,
            BillDate = request.Data.BillDate,
            BillStatus = request.Data.BillStatus,
            Description = request.Data.Description,
            PurchaseOrderId = request.Data.PurchaseOrderId
        };

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

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