<?php

namespace App\Models;

use App\Support\ProjectTutorialVideo;
use Illuminate\Database\Eloquent\Model;

class SessionVideo extends Model
{
    protected $fillable = ['session_id', 'title', 'source_type', 'source_path', 'thumbnail_path', 'duration', 'order'];

    public function session()
    {
        return $this->belongsTo(CourseSession::class, 'session_id');
    }

    public function progresses()
    {
        return $this->hasMany(VideoProgress::class, 'video_id');
    }

    public function getPlayerTypeAttribute(): string
    {
        if ($this->source_type === 'file') {
            return 'file';
        }

        $resolved = ProjectTutorialVideo::playerForLink((string) ($this->source_path ?? ''));

        return ($resolved['type'] ?? '') === 'video' ? 'file' : 'embed';
    }

    public function getPlayerSrcAttribute(): string
    {
        $url = trim((string) ($this->source_path ?? ''));

        if ($this->source_type === 'file') {
            return $url;
        }

        $resolved = ProjectTutorialVideo::playerForLink($url);

        return (string) (($resolved['src'] ?? '') ?: $url);
    }

    public function getThumbnailUrlAttribute(): ?string
    {
        if (!empty($this->thumbnail_path)) {
            return public_asset_url($this->thumbnail_path);
        }

        if ($this->source_type === 'file') {
            return null;
        }

        $thumb = ProjectTutorialVideo::thumbnailForLink((string) ($this->source_path ?? ''));

        return $thumb !== '' ? $thumb : null;
    }
}
