<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Lesson extends Model
{
    protected $guarded = [];

    protected $casts = [
        'is_free_preview' => 'boolean',
        'materials' => 'array',
    ];

    public function module(): BelongsTo
    {
        return $this->belongsTo(CourseModule::class, 'course_module_id');
    }

    public function completedBy(): BelongsToMany
    {
        return $this->belongsToMany(User::class)->withPivot('completed_at')->withTimestamps();
    }

    /**
     * Embeddable iframe URL for the lesson video. Handles YouTube (owned
     * content) and Wistia (the Money-Wise Academy host); falls back to the
     * raw URL for anything else.
     */
    public function videoEmbedUrl(): ?string
    {
        if (! $this->video_url) {
            return null;
        }

        if (preg_match('/(?:youtu\.be\/|v=|embed\/)([\w-]{11})/', $this->video_url, $m)) {
            return "https://www.youtube-nocookie.com/embed/{$m[1]}";
        }

        if (preg_match('#wistia(?:\.com|\.net)/(?:embed/)?(?:iframe/|medias/)?([A-Za-z0-9]{8,12})#', $this->video_url, $m)) {
            return "https://fast.wistia.net/embed/iframe/{$m[1]}";
        }

        return $this->video_url;
    }

    /** Back-compat alias. */
    public function youtubeEmbedUrl(): ?string
    {
        return $this->videoEmbedUrl();
    }
}
