<?php

namespace App\Http\Controllers\Api\Billing;

use App\Domains\Billing\Actions\ReconcileOrderPaymentsAction;
use App\Domains\Billing\Actions\ActivateTenantPlanFromInvoiceAction;
use App\Domains\Billing\Models\PaymentProvider;
use App\Domains\Billing\Models\PaymentRequest;
use App\Domains\Billing\Models\PaymentWebhookEvent;
use App\Domains\Billing\Models\TenantBillingInvoice;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WhishWebhookController extends Controller
{
    public function __invoke(
        Request $request,
        ReconcileOrderPaymentsAction $reconcile,
        ActivateTenantPlanFromInvoiceAction $activateTenantPlan
    ): JsonResponse {
        $payload = $request->all();
        $paymentRequest = PaymentRequest::query()
            ->where('external_reference', $payload['external_reference'] ?? null)
            ->first();
        $provider = $paymentRequest?->provider ?: PaymentProvider::query()->where('provider_key', 'whish')->firstOrFail();

        $event = PaymentWebhookEvent::query()->create([
            'tenant_id' => $provider->tenant_id,
            'payment_provider_id' => $provider->getKey(),
            'provider_key' => 'whish',
            'external_event_id' => $payload['external_event_id'] ?? null,
            'payload_json' => $payload,
            'processing_status' => 'received',
            'created_at' => now(),
        ]);

        if ($paymentRequest) {
            $reconcile->execute($provider, $paymentRequest, $payload);
            $event->update([
                'processing_status' => 'processed',
                'processed_at' => now(),
            ]);

            return response()->json(['status' => 'ok']);
        }

        $invoice = TenantBillingInvoice::query()
            ->where('external_reference', $payload['external_reference'] ?? null)
            ->first();

        if ($invoice) {
            $activateTenantPlan->execute($invoice);
            $event->update([
                'processing_status' => 'processed',
                'processed_at' => now(),
            ]);
        }

        return response()->json(['status' => 'ok']);
    }
}
