<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\Branch;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class BranchContextController extends Controller
{
    public function update(Request $request, string $branch): RedirectResponse
    {
        if ($branch === 'consolidado') {
            abort_unless($request->user()->canUseConsolidatedView(), 403);
            session()->put('active_branch_id', null);
            $description = 'Visão consolidada activada';
        } else {
            $selected = Branch::query()->whereKey($branch)->where('is_active', true)->firstOrFail();
            abort_unless($request->user()->canAccessBranch($selected->id), 403);
            session()->put('active_branch_id', $selected->id);
            $description = 'Contexto alterado para '.$selected->name;
        }

        AuditLog::query()->create([
            'actor_id' => $request->user()->id,
            'branch_id' => session('active_branch_id'),
            'event' => 'filial_alterada',
            'description' => $description,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return back()->with('success', $description.'.');
    }
}
