<?php

namespace App\Http\Controllers\Portal;

use App\Domain\Identity\Services\PortalInvitationService;
use App\Domain\Shared\Exceptions\DomainException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;

/**
 * Activation lives in a plain controller on purpose.
 *
 * A Livewire component holds its state in public properties, and every one of
 * those is serialised into the page and sent back on every round-trip. A
 * single-use activation token in a public property is a token in the DOM, in
 * the browser's history, in any proxy log — and, before that page was gated, in
 * the 500 error page's request dump.
 */
class InvitationController extends Controller
{
    public function __construct(private readonly PortalInvitationService $invitations) {}

    public function show(Request $request, string $token)
    {
        // Missing, expired, revoked and already-used all render the same page.
        // Distinguishing them tells whoever is guessing which tokens exist.
        $invitation = $this->invitations->findLive($token);

        if (! $invitation) {
            return response()->view('portal.invitation-invalid', [], 410);
        }

        return view('portal.invitation-activate', [
            'token' => $token,
            'personName' => $invitation->person?->name_ar ?? $invitation->person?->name,
            'needsEmail' => true,
        ]);
    }

    public function store(Request $request, string $token)
    {
        // Guessing is throttled by IP, since there is no account to throttle by
        // until the token resolves.
        $key = 'portal-activate:' . $request->ip();

        if (RateLimiter::tooManyAttempts($key, 10)) {
            return response()->view('portal.invitation-invalid', [
                'message' => __('محاولات كثيرة. حاول مرة أخرى بعد قليل.'),
            ], 429);
        }

        RateLimiter::hit($key, 900);

        $data = $request->validate([
            'password' => ['required', 'string', 'min:8', 'max:200', 'confirmed'],
            'email' => ['nullable', 'email', 'max:255'],
        ], [
            'password.required' => __('كلمة المرور مطلوبة'),
            'password.min' => __('كلمة المرور يجب ألا تقل عن ٨ أحرف'),
            'password.confirmed' => __('تأكيد كلمة المرور غير مطابق'),
            'email.email' => __('البريد الإلكتروني غير صالح'),
        ]);

        try {
            $user = $this->invitations->activate($token, $data['password'], $data['email'] ?? null);
        } catch (DomainException $e) {
            throw ValidationException::withMessages(['password' => $e->getMessage()]);
        }

        Auth::login($user, remember: true);
        $request->session()->regenerate();

        RateLimiter::clear($key);

        return redirect()->route('portal.home');
    }
}
