<?php

namespace App\Http\Controllers;

use App\Models\TeamInvitation;
use App\Models\User;
use App\Models\WorkspaceUser;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class TeamInvitationAcceptController extends Controller
{
    /**
     * Handle team invitation acceptance.
     */
    public function __invoke(string $token): Response|RedirectResponse
    {
        $invitation = TeamInvitation::where('token', $token)->first();

        if (! $invitation) {
            return Inertia::render('auth/InvitationError', [
                'title' => 'Invitation introuvable',
                'message' => 'Ce lien d\'invitation est invalide ou n\'existe pas.',
                'homeUrl' => url('/'),
            ]);
        }

        if (! $invitation->isValid()) {
            $message = $invitation->accepted_at !== null
                ? 'Cette invitation a déjà été acceptée.'
                : 'Cette invitation a expiré.';

            return Inertia::render('auth/InvitationError', [
                'title' => 'Invitation invalide',
                'message' => $message,
                'homeUrl' => url('/'),
            ]);
        }

        if (Auth::check()) {
            return $this->handleAuthenticatedUser($invitation);
        }

        return $this->handleUnauthenticatedUser($invitation);
    }

    /**
     * Handle invitation acceptance for authenticated users.
     */
    protected function handleAuthenticatedUser(TeamInvitation $invitation): Response|RedirectResponse
    {
        /** @var User $user */
        $user = Auth::user();

        if (strtolower($user->email) !== strtolower($invitation->email)) {
            return Inertia::render('auth/InvitationError', [
                'title' => 'Adresse email incorrecte',
                'message' => 'Cette invitation est destinée à une autre adresse email.',
                'homeUrl' => url('/'),
            ]);
        }

        $alreadyMember = WorkspaceUser::where('workspace_id', $invitation->workspace_id)
            ->where('user_id', $user->id)
            ->exists();

        if ($alreadyMember) {
            return redirect()->route('dashboard')->with('info', 'Vous êtes déjà membre de cet espace de travail.');
        }

        DB::transaction(function () use ($user, $invitation) {
            $user->workspaces()->attach($invitation->workspace_id, [
                'role' => $invitation->role,
                'permissions' => json_encode(config("permissions.defaults.{$invitation->role}", [])),
            ]);

            $invitation->update(['accepted_at' => now()]);
        });

        session(['current_workspace_id' => $invitation->workspace_id]);

        return redirect()->route('dashboard')->with('success', 'Vous avez rejoint l\'espace de travail avec succès.');
    }

    /**
     * Handle invitation acceptance for unauthenticated users.
     */
    protected function handleUnauthenticatedUser(TeamInvitation $invitation): RedirectResponse
    {
        $existingUser = User::where('email', $invitation->email)->first();

        if ($existingUser) {
            return redirect()
                ->to(route('login', ['invitation' => $invitation->token]))
                ->with('status', 'Connectez-vous pour rejoindre l\'espace de travail');
        }

        return redirect()->to(route('register', ['invitation' => $invitation->token]));
    }
}
