<?php

namespace App\Http\Middleware;

use App\Models\ApiToken;
use App\Models\User;
use App\Support\Authorization\PermissionCatalog;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateApiToken
{
    public function handle(Request $request, Closure $next): Response
    {
        $token = ApiToken::findFromPlainTextToken($this->resolvePlainTextToken($request));

        if (! $token || ! $token->user) {
            return response()->json(['message' => 'Token API inválido.'], 401);
        }

        $user = $token->user;
        $isOwnerUser = in_array($user->role, [User::ROLE_CLIENT, User::ROLE_OWNER_STAFF], true);

        if (
            ! $user->is_active
            || ! $isOwnerUser
            || (int) $user->organization_id <= 0
            || (int) $user->organization_id !== (int) $token->organization_id
        ) {
            return response()->json(['message' => 'El usuario del token no tiene acceso API.'], 403);
        }

        app('auth')->guard('web')->setUser($user);
        $request->setUserResolver(fn () => $user);
        $request->attributes->set('apiToken', $token);
        setPermissionsTeamId((int) ($user->organization_id ?? PermissionCatalog::GLOBAL_TEAM_ID));

        $token->forceFill(['last_used_at' => now()])->save();

        return $next($request);
    }

    private function resolvePlainTextToken(Request $request): ?string
    {
        $bearerToken = trim((string) $request->bearerToken());
        if ($bearerToken !== '') {
            return $bearerToken;
        }

        if ($request->routeIs('api.v1.docs', 'api.v1.openapi')) {
            return trim((string) $request->query('api_token'));
        }

        return null;
    }
}
