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

namespace Indotalent.Features.Sales.SalesQuotation.Cqrs;

public class UpdateSalesQuotationRequest
{
    public string? Id { get; set; }
    public DateTime? QuotationDate { get; set; }
    public Data.Enums.SalesQuotationStatus QuotationStatus { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public string? CustomerId { get; set; }
    public string? TaxId { 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 UpdateSalesQuotationCommand(UpdateSalesQuotationRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.QuotationDate = request.Data.QuotationDate;
        entity.QuotationStatus = request.Data.QuotationStatus;
        entity.Description = request.Data.Description;
        entity.CustomerId = request.Data.CustomerId;
        entity.TaxId = request.Data.TaxId;

        await _context.SaveChangesAsync(cancellationToken);

        if (!string.IsNullOrEmpty(entity.Id))
        {
            SalesQuotationHelper.Recalculate(_context, entity.Id);
        }

        return true;
    }
}