<?php

namespace App\Models;

use Database\Factories\PlatformChannelFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

/**
 * @method static findMany(mixed $channel_ids)
 * @method static create(array<string, mixed> $array)
 *
 * @property int $id
 * @property int $platform_instance_id
 * @property PlatformInstance $platformInstance
 * @property int $channel_id
 * @property string $name
 * @property string $display_name
 * @property string|null $description
 * @property int|null $language_id
 * @property Language|null $language
 * @property bool $is_active
 */
class PlatformChannel extends Model
{
    /** @use HasFactory<PlatformChannelFactory> */
    use HasFactory;

    protected $table = 'platform_channels';

    protected $fillable = [
        'platform_instance_id',
        'name',
        'display_name',
        'channel_id',
        'description',
        'language_id',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'channel_id' => 'integer',
    ];

    /**
     * @return BelongsTo<PlatformInstance, $this>
     */
    public function platformInstance(): BelongsTo
    {
        return $this->belongsTo(PlatformInstance::class);
    }

    /**
     * @return BelongsToMany<PlatformAccount, $this>
     */
    public function platformAccounts(): BelongsToMany
    {
        return $this->belongsToMany(PlatformAccount::class, 'platform_account_channels')
            ->withPivot(['is_active', 'priority'])
            ->withTimestamps();
    }

    /**
     * @return BelongsToMany<PlatformAccount, $this>
     */
    public function activePlatformAccounts(): BelongsToMany
    {
        return $this->platformAccounts()->wherePivot('is_active', true);
    }

    public function getFullNameAttribute(): string
    {
        // For Lemmy, use /c/ prefix
        return $this->platformInstance->url.'/c/'.$this->name;
    }

    /**
     * @return BelongsToMany<Feed, $this>
     */
    public function feeds(): BelongsToMany
    {
        return $this->belongsToMany(Feed::class, 'routes')
            ->withPivot(['is_active', 'priority'])
            ->withTimestamps();
    }

    /**
     * @return BelongsToMany<Feed, $this>
     */
    public function activeFeeds(): BelongsToMany
    {
        return $this->feeds()
            ->wherePivot('is_active', true)
            ->orderByPivot('priority', 'desc');
    }

    /**
     * @return BelongsTo<Language, $this>
     */
    public function language(): BelongsTo
    {
        return $this->belongsTo(Language::class);
    }
}
