<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class OperatingModeController extends Controller
{
    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'mode' => ['required', Rule::in(['operation', 'administration'])],
        ]);

        if ($validated['mode'] === 'administration') {
            abort_unless($request->user()->hasPrivilegedRole(), 403, 'Não possui um perfil administrativo.');
            session()->put('administration_mode_started_at', now());
        } else {
            session()->forget('administration_mode_started_at');
        }

        session()->put('operating_mode', $validated['mode']);

        AuditLog::query()->create([
            'actor_id' => $request->user()->id,
            'branch_id' => session('active_branch_id'),
            'event' => 'modo_alterado',
            'description' => $validated['mode'] === 'administration' ? 'Modo de Administração activado' : 'Modo Normal activado',
            'new_values' => ['mode' => $validated['mode']],
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return back()->with('success', 'Modo de trabalho actualizado.');
    }
}
