<?php

namespace App\Http\Controllers\Owner;

use App\Http\Controllers\Controller;
use App\Support\OwnerWorkspace;
use Illuminate\Http\Request;

class WorkspaceController extends Controller
{
    public function switch(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if ($organizationId <= 0) {
            abort(403);
        }

        $validated = $request->validate([
            'mariachi_group_id' => ['nullable', 'integer', 'min:1'],
        ]);

        $groupId = (int) ($validated['mariachi_group_id'] ?? 0);
        if ($groupId > 0) {
            $isValid = OwnerWorkspace::canAccessGroup($request->user(), $groupId);

            if (!$isValid) {
                return back()->withErrors([
                    'workspace' => 'El equipo seleccionado no es válido para esta cuenta.',
                ]);
            }
        }

        OwnerWorkspace::setActiveGroupId($request, $groupId > 0 ? $groupId : null);

        return back()->with('status', 'Equipo activo actualizado.');
    }
}
