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

namespace Indotalent.Features.Sales.CreditNote.Cqrs;

public class UpdateCreditNoteRequest
{
    public string? Id { get; set; }
    public DateTime? CreditNoteDate { get; set; }
    public Data.Enums.CreditNoteStatus CreditNoteStatus { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public string? SalesReturnId { 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 UpdateCreditNoteCommand(UpdateCreditNoteRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.CreditNoteDate = request.Data.CreditNoteDate;
        entity.CreditNoteStatus = request.Data.CreditNoteStatus;
        entity.Description = request.Data.Description;
        entity.SalesReturnId = request.Data.SalesReturnId;

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