<?php

namespace App\Services\Frontend;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class LandingPageRoleService
{
    public function resolveRole(?User $user): string
    {
        if (!$user) {
            return 'guest';
        }

        $roles = DB::table('user_roles as ur')
            ->join('roles as r', 'r.id', '=', 'ur.role_id')
            ->where('ur.user_id', $user->id)
            ->whereNull('ur.deleted_at')
            ->orderBy('r.priority', 'asc')
            ->pluck('r.name')
            ->map(fn ($r) => strtolower((string) $r))
            ->all();

        if (!empty($roles)) {
            return $roles[0];
        }

        return 'guest';
    }
}
