<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Filament\Pages\Monitoring\FindingExceptionsQueue;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Support\Auth\Capabilities;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

final class OpenFindingExceptionsQueueController extends Controller
{
    public function __invoke(Request $request, ManagedEnvironment $environment): RedirectResponse
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            abort(403);
        }

        $workspace = Workspace::query()->whereKey($environment->workspace_id)->first();

        if (! $workspace instanceof Workspace) {
            abort(404);
        }

        if (! $user->canAccessTenant($environment)) {
            abort(404);
        }

        $workspaceContext = app(WorkspaceContext::class);

        if (! $workspaceContext->isMember($user, $workspace)) {
            abort(404);
        }

        /** @var WorkspaceCapabilityResolver $resolver */
        $resolver = app(WorkspaceCapabilityResolver::class);

        if (! $resolver->can($user, $workspace, Capabilities::FINDING_EXCEPTION_APPROVE)) {
            abort(404);
        }

        $workspaceContext->setCurrentWorkspace($workspace, $user, $request);

        if (! $workspaceContext->rememberEnvironmentContext($environment, $request)) {
            abort(404);
        }

        return redirect()->to(FindingExceptionsQueue::getUrl([
            'tenant' => (string) $environment->external_id,
        ], panel: 'admin'));
    }
}
