<?php

namespace App\Models\Tutorials;

use App\Models\Auth\User;
use App\Models\Products\Product;
use App\Services\Tutorials\VideoUrlService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Tutorial extends Model
{
    use HasFactory;

    protected $table = 'tutorials';

    protected $fillable = [
        'tutorial_version_id',
        'videoid',
        'platform',
        'title',
        'desc',
        'status',
        'sort_order',
        'created_by',
    ];

    protected $casts = [
        'sort_order' => 'integer',
    ];

    /* -----------------------------
       Relaciones
    ------------------------------*/

    /**
     * Versión a la que pertenece el tutorial
     */
    public function tutorialVersion()
    {
        return $this->belongsTo(TutorialVersion::class, 'tutorial_version_id');
    }

    /**
     * Producto al que pertenece el tutorial (a través de tutorialVersion)
     */
    public function product()
    {
        return $this->hasOneThrough(Product::class, TutorialVersion::class, 'id', 'id', 'tutorial_version_id', 'product_id');
    }

    /**
     * Usuario que creó el tutorial
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /* -----------------------------
       Scopes
    ------------------------------*/

    /**
     * Scope para filtrar tutoriales publicados
     */
    public function scopePublished($query)
    {
        return $query->where('status', 'published');
    }

    /**
     * Scope para filtrar tutoriales en borrador
     */
    public function scopeDraft($query)
    {
        return $query->where('status', 'draft');
    }

    /**
     * Scope para filtrar tutoriales archivados
     */
    public function scopeArchived($query)
    {
        return $query->where('status', 'archived');
    }

    /**
     * Scope para filtrar por producto (a través de tutorialVersion)
     */
    public function scopeForProduct($query, $product)
    {
        $productId = $product instanceof Product ? $product->id : $product;
        return $query->whereHas('tutorialVersion', function ($q) use ($productId) {
            $q->where('product_id', $productId);
        });
    }

    /**
     * Scope para ordenar por sort_order
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc');
    }

    /* -----------------------------
       Accessors
    ------------------------------*/

    /**
     * Obtiene la URL completa del vídeo
     */
    public function getVideoUrlAttribute(): string
    {
        return VideoUrlService::buildUrl($this->platform, $this->videoid);
    }

    /**
     * Obtiene la URL de embed para iframe
     */
    public function getEmbedUrlAttribute(): string
    {
        return VideoUrlService::buildEmbedUrl($this->platform, $this->videoid);
    }
}








