<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;

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

    protected $casts = [
        'outcomes' => 'array',
        'is_published' => 'boolean',
    ];

    public function modules(): HasMany
    {
        return $this->hasMany(CourseModule::class)->orderBy('sort');
    }

    public function lessons(): HasManyThrough
    {
        return $this->hasManyThrough(Lesson::class, CourseModule::class)
            ->orderBy('course_modules.sort')
            ->orderBy('lessons.sort');
    }

    public function enrollments(): HasMany
    {
        return $this->hasMany(Enrollment::class);
    }

    public function coverUrl(): string
    {
        if (! $this->cover_path) {
            return asset('images/investable-intro.png');
        }

        return \Illuminate\Support\Str::startsWith($this->cover_path, 'images/')
            ? asset($this->cover_path)
            : asset('storage/'.$this->cover_path);
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }
}
