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

namespace Indotalent.Features.Purchase.DebitNote.Cqrs;

public class UpdateDebitNoteRequest
{
    public string? Id { get; set; }
    public DateTime? DebitNoteDate { get; set; }
    public Data.Enums.DebitNoteStatus DebitNoteStatus { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public string? PurchaseReturnId { get; set; }
    public decimal? BeforeTaxAmount { get; set; }
    public decimal? TaxAmount { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateDebitNoteCommand(UpdateDebitNoteRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.DebitNoteDate = request.Data.DebitNoteDate;
        entity.DebitNoteStatus = request.Data.DebitNoteStatus;
        entity.Description = request.Data.Description;
        entity.PurchaseReturnId = request.Data.PurchaseReturnId;

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}