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

namespace Indotalent.Features.Sales.Invoice.Cqrs;

public class UpdateInvoiceRequest
{
    public string? Id { get; set; }
    public DateTime? InvoiceDate { get; set; }
    public Data.Enums.InvoiceStatus InvoiceStatus { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public string? SalesOrderId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdateInvoiceCommand(UpdateInvoiceRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.InvoiceDate = request.Data.InvoiceDate;
        entity.InvoiceStatus = request.Data.InvoiceStatus;
        entity.Description = request.Data.Description;
        entity.SalesOrderId = request.Data.SalesOrderId;

        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}