<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class KnowledgeBase extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * 可批量赋值的属性
     *
     * @var array<string>
     */
    protected $fillable = [
        'name',
        'description',
        'status',
    ];

    /**
     * 获取知识库下的文档
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function documents()
    {
        return $this->hasMany(Document::class);
    }

    /**
     * 获取知识库关联的线站
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function stations()
    {
        return $this->belongsToMany(Station::class);
    }

    /**
     * 按用户线站过滤：全局 KB（无线站关联）+ 用户线站关联的 KB
     */
    public function scopeAccessibleBy(Builder $query, User $user): Builder
    {
        if (!$user->hasStationRestriction()) {
            return $query;
        }

        $stationIds = $user->getAccessibleStationIds();

        return $query->where(function (Builder $q) use ($stationIds) {
            $q->whereDoesntHave('stations')
              ->orWhereHas('stations', fn ($sq) => $sq->whereIn('stations.id', $stationIds));
        });
    }
}
