<?php

namespace App\Http\Controllers\View;

use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\RedirectResponse;

class DashboardRedirectController extends Controller
{
    public function __construct(protected Role $role)
    {
    }

    public function dashboard(): RedirectResponse
    {
        $session = session();
        $roles   = $session->get('roles') ?? [];

        if (empty($roles) && $session->has('role')) {
            $roles = [$session->get('role')];
        }

        return $this->redirectToDashboard($roles);
    }

    private function redirectToDashboard(array $roles): RedirectResponse
    {
        if (empty($roles)) {
            log_message('error', 'Empty roles array passed to redirectToDashboard.');
            return redirect()->to('/landing_page/guest_dashboard');
        }

        $rows = $this->role->findByNamesOrSlugs($roles);

        if (!empty($rows)) {
            $route = $rows[0]['dashboard_route'] ?? '/landing_page/guest_dashboard';
            log_message('debug', 'Redirecting user to: ' . $route);
            return redirect()->to($route);
        }

        log_message('warning', 'No matching role found. Redirecting to guest dashboard.');
        return redirect()->to('/landing_page/guest_dashboard');
    }
}
