<?php

namespace App\Http\Controllers\Store;

use App\Enums\ConsentChannel;
use App\Enums\ConsentSource;
use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Services\Consent\MarketingConsentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class UnsubscribeController extends Controller
{
    public function __construct(private readonly MarketingConsentService $service) {}

    public function show(Request $request)
    {
        // Signed middleware already validated. Pull params from query.
        $client = Client::findOrFail((int) $request->query('client'));
        $channel = ConsentChannel::tryFrom((string) $request->query('channel')) ?? abort(404);

        return view('store.unsubscribe.confirm', compact('client', 'channel'));
    }

    public function confirm(Request $request)
    {
        $client = Client::findOrFail((int) $request->query('client'));
        $channel = ConsentChannel::tryFrom((string) $request->query('channel')) ?? abort(404);

        $this->service->withdraw($client, $channel, ConsentSource::UNSUBSCRIBE_LINK, $request);

        // PRC-622 — 'Unsubscribe Confirmation' maili
        // (config/communication_events.php eşlemesi).
        app(\App\Core\Hook\HookBridge::class)->fireAction('SubscriberUnsubscribed', [
            'client_id' => $client->id,
            'email' => $client->email,
            'channel' => $channel->value,
        ]);

        return view('store.unsubscribe.confirm', [
            'client' => $client,
            'channel' => $channel,
            'done' => true,
        ]);
    }

    /**
     * Helper for templates: build a signed URL pointing at the GET route.
     * Used by P2-T10 footer injection.
     */
    public static function signedUrlFor(Client $client, ConsentChannel $channel): string
    {
        return URL::signedRoute('unsubscribe.show', [
            'client' => $client->id,
            'channel' => $channel->value,
        ]);
    }
}
