<?php

namespace App\Models;

use App\Enums\PlatformEnum;
use Database\Factories\PlatformInstanceFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * @method static updateOrCreate(array<string, mixed> $array, $instanceData)
 * @method static where(string $string, mixed $operator)
 *
 * @property PlatformEnum $platform
 * @property string $url
 * @property string $name
 * @property string $description
 * @property bool $is_active
 */
class PlatformInstance extends Model
{
    /** @use HasFactory<PlatformInstanceFactory> */
    use HasFactory;

    protected $fillable = [
        'platform',
        'url',
        'name',
        'description',
        'is_active',
    ];

    protected $casts = [
        'platform' => PlatformEnum::class,
        'is_active' => 'boolean',
    ];

    /**
     * @return HasMany<PlatformChannel, $this>
     */
    public function channels(): HasMany
    {
        return $this->hasMany(PlatformChannel::class);
    }

    /**
     * @return BelongsToMany<Language, $this>
     */
    public function languages(): BelongsToMany
    {
        return $this->belongsToMany(Language::class)
            ->withPivot(['platform_language_id', 'is_default'])
            ->withTimestamps();
    }

    public static function findByUrl(PlatformEnum $platform, string $url): ?self
    {
        return static::where('platform', $platform)
            ->where('url', $url)
            ->first();
    }
}
