using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Purchase.Bill.Cqrs;

public class UpdateBillRequest
{
    public string? Id { get; set; }
    public DateTime? BillDate { get; set; }
    public Data.Enums.BillStatus BillStatus { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public string? PurchaseOrderId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateBillCommand(UpdateBillRequest Data) : IRequest<bool>;

public class UpdateBillHandler : IRequestHandler<UpdateBillCommand, bool>
{
    private readonly AppDbContext _context;
    public UpdateBillHandler(AppDbContext context) => _context = context;

    public async Task<bool> Handle(UpdateBillCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Bill
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null) return false;

        entity.BillDate = request.Data.BillDate;
        entity.BillStatus = request.Data.BillStatus;
        entity.Description = request.Data.Description;
        entity.PurchaseOrderId = request.Data.PurchaseOrderId;

        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}