<?php

namespace App\Http\Controllers\Store;

use App\Core\Addon\AddonContext;
use App\Core\Addon\AddonManager;
use App\Http\Controllers\Controller;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ClientareaAddonDispatchController extends Controller
{
    public function __construct(protected AddonManager $manager) {}

    public function __invoke(Request $request, string $name, ?string $action = null, ?string $params = null)
    {
        $addon = $this->manager->get($name);
        if (! $addon || ! $this->manager->isActive($name)) {
            abort(404);
        }

        // Resolve active client: switched-user session takes precedence
        $client = null;
        if (Auth::guard('client')->check()) {
            $clientId = session('active_client_id') ?? Auth::guard('client')->id();
            $client = Client::find($clientId);
        }

        $bridge = app(\App\Core\Hook\HookBridge::class);
        $bridge->fireAction('ClientAreaPageAddonModule', array_merge(
            $client ? $bridge->buildClientContext($client) : [],
            ['addon' => $name, 'addon_action' => $action]
        ));

        $ctx = AddonContext::clientarea($request, $action, $params, $client);

        // PRC-1112 — output fault-isolation. Buggy bir addon'un clientareaOutput()'u
        // client sayfasını 500'lemesin. Yakala + logla + graceful degrade: kırık
        // addon = kullanılamıyor → 404 (isActive()==false yoluyla tutarlı). Debug'da
        // geliştirici gerçek hatayı görsün diye yeniden fırlat.
        try {
            return $addon->clientareaOutput($ctx);
        } catch (\Throwable $e) {
            Log::error('Addon clientareaOutput failed', [
                'addon' => $name,
                'action' => $action,
                'error' => $e->getMessage(),
            ]);

            if (config('app.debug')) {
                throw $e;
            }

            abort(404);
        }
    }
}
