<?php

namespace App\Http\Controllers;

use App\Http\Requests\SwitchWorkspaceRequest;
use Illuminate\Http\RedirectResponse;

class WorkspaceSwitchController extends Controller
{
    /**
     * Switch the current workspace.
     */
    public function __invoke(SwitchWorkspaceRequest $request): RedirectResponse
    {
        $workspaceId = (int) $request->validated('workspace_id');

        $user = $request->user();
        $hasAccess = $user->workspaces()->where('workspaces.id', $workspaceId)->exists();

        if (! $hasAccess) {
            return redirect()->route('dashboard');
        }

        $previousWorkspaceId = $request->session()->get('current_workspace_id');

        if ($previousWorkspaceId === $workspaceId) {
            return redirect()->route('dashboard');
        }

        $request->session()->put('current_workspace_id', $workspaceId);

        activity()
            ->causedBy($user)
            ->withProperties([
                'previous_workspace_id' => $previousWorkspaceId,
                'new_workspace_id' => $workspaceId,
            ])
            ->log('Switched workspace');

        return redirect()->route('dashboard');
    }
}
