<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class RoleNavItem extends BaseModel
{
    protected $table = 'role_nav_items';

    public $timestamps = true;

    protected $fillable = [
        'role_id',
        'nav_item_id',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'role_id'     => 'integer',
        'nav_item_id' => 'integer',
        'created_at'  => 'datetime',
        'updated_at'  => 'datetime',
    ];

    /* ============================================================
     * Relationships (optional)
     * ============================================================
     */

    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class, 'role_id');
    }

    public function navItem(): BelongsTo
    {
        return $this->belongsTo(NavItem::class, 'nav_item_id');
    }

    /* ============================================================
     * Scopes
     * ============================================================
     */

    public function scopeForRoles(Builder $q, array $roleIds): Builder
    {
        $roleIds = array_values(array_unique(array_filter(array_map('intval', $roleIds))));
        return empty($roleIds) ? $q->whereRaw('1=0') : $q->whereIn('role_id', $roleIds);
    }

    /* ============================================================
     * Business: role names -> allowed nav_item_ids
     * ============================================================
     */

    /**
     * Accepts role names (strings from session), resolves to role IDs, then returns allowed nav_item_ids.
     */
    public static function getNavItemIdsForRoles(array $roleNames): array
    {
        $roleNames = array_values(array_filter(array_map('strval', $roleNames)));
        if (empty($roleNames)) return [];

        // Uses the Role model you converted earlier
        $roleIds = Role::getIdsByNames($roleNames);
        if (empty($roleIds)) return [];

        // pluck nav_item_id, unique, sorted (optional)
        return static::query()
            ->select('nav_item_id')
            ->whereIn('role_id', $roleIds)
            ->pluck('nav_item_id')
            ->map(fn ($v) => (int) $v)
            ->unique()
            ->values()
            ->all();
    }

    /* ============================================================
     * Optional validation helper
     * ============================================================
     */

    public static function rules(bool $updating = false): array
    {
        return [
            'role_id'     => [$updating ? 'sometimes' : 'required', 'integer', 'min:1', 'exists:roles,id'],
            'nav_item_id' => [$updating ? 'sometimes' : 'required', 'integer', 'min:1', 'exists:nav_items,id'],
        ];
    }
}