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

namespace Indotalent.Features.Sales.SalesOrder.Cqrs;

public class UpdateSalesOrderRequest
{
    public string? Id { get; set; }
    public DateTime? OrderDate { get; set; }
    public Data.Enums.SalesOrderStatus OrderStatus { 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 UpdateSalesOrderCommand(UpdateSalesOrderRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.OrderDate = request.Data.OrderDate;
        entity.OrderStatus = request.Data.OrderStatus;
        entity.Description = request.Data.Description;
        entity.CustomerId = request.Data.CustomerId;
        entity.TaxId = request.Data.TaxId;

        await _context.SaveChangesAsync(cancellationToken);

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

        return true;
    }
}