<?php

namespace App\Services\Dashboard;

use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class DashboardRouteService
{
    private const FALLBACK_ROUTE = '/landing_page/guest_dashboard';

    public function resolveForUser(?User $user): array
    {
        if (!$user) {
            Log::warning('Dashboard route requested without an authenticated user.');
            return [
                'route' => self::FALLBACK_ROUTE,
                'role' => null,
                'role_slug' => null,
                'roles' => [],
            ];
        }

        $roles = $user->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->toArray();

        if (empty($roles)) {
            Log::warning('Dashboard route requested with no roles assigned.', [
                'user_id' => $user->id,
            ]);

            return [
                'route' => self::FALLBACK_ROUTE,
                'role' => null,
                'role_slug' => null,
                'roles' => [],
            ];
        }

        $rows = Role::findByNamesOrSlugs($roles);

        if (!empty($rows)) {
            $role = $rows[0];
            $route = $role->dashboard_route ?: self::FALLBACK_ROUTE;

            return [
                'route' => $route,
                'role' => $role->name ?? null,
                'role_slug' => $role->slug ?? null,
                'roles' => $roles,
            ];
        }

        Log::warning('No matching role dashboard route found.', [
            'user_id' => $user->id,
            'roles' => $roles,
        ]);

        return [
            'route' => self::FALLBACK_ROUTE,
            'role' => null,
            'role_slug' => null,
            'roles' => $roles,
        ];
    }
}
