<?php

namespace App\Domains\Billing\Actions;

use App\Domains\Billing\Models\PaymentProvider;
use App\Domains\Billing\Models\PaymentRequest;
use App\Domains\Billing\Models\PaymentTransaction;
use App\Domains\Billing\Services\PaymentProviderManager;

class ReconcileOrderPaymentsAction
{
    public function __construct(
        protected PaymentProviderManager $providerManager,
    ) {
    }

    public function execute(PaymentProvider $provider, PaymentRequest $request, array $payload): void
    {
        $driver = $this->providerManager->driver($provider->provider_key);
        $result = $driver->reconcileTransaction($provider, $request, $payload);

        $request->update([
            'status' => $result['payment_request_status'],
        ]);

        PaymentTransaction::query()->create([
            'tenant_id' => $request->tenant_id,
            'payment_request_id' => $request->getKey(),
            'status' => $result['payment_request_status'],
            'provider_reference' => $payload['provider_reference'] ?? $payload['external_reference'] ?? null,
            'amount' => $request->amount,
            'currency_code' => $request->currency_code,
            'payload_json' => $payload,
            'processed_at' => now(),
        ]);

        $request->order()->update([
            'payment_status' => $result['order_payment_status'],
        ]);
    }
}
