<?php

declare(strict_types=1);

namespace Kylin\Education\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\Education\Enums\CourseStatus;
use Kylin\Education\Enums\CourseType;

/**
 * 课程模型
 *
 * 在线教育课程，支持图文、视频、音频等多种课程类型。
 *
 * @property int          $id
 * @property string       $title         课程标题
 * @property string       $description   课程描述
 * @property CourseType   $type          课程类型
 * @property CourseStatus $status        课程状态
 * @property int          $category_id   分类 ID
 * @property-read CourseCategory $category  分类
 * @property-read CourseChapter[] $chapters  章节
 */
class Course extends Model
{
    protected $table = 'courses';

    protected $fillable = [
        'name',
        'code',
        'category_id',
        'type',
        'hours',
        'duration',
        'max_students',
        'price',
        'age_range',
        'description',
        'cover_image',
        'status',
        'teacher_id',
    ];

    protected $casts = [
        'type' => CourseType::class,
        'status' => CourseStatus::class,
        'hours' => 'integer',
        'duration' => 'integer',
        'max_students' => 'integer',
        'price' => 'decimal:2',
    ];

    /**
     * 关联教师
     */
    public function teacher(): BelongsTo
    {
        return $this->belongsTo(config('auth.providers.users.model', \App\Models\User::class), 'teacher_id');
    }

    /**
     * 关联分类
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(CourseCategory::class, 'category_id');
    }

    /**
     * 关联章节
     */
    public function chapters(): HasMany
    {
        return $this->hasMany(CourseChapter::class, 'course_id')->orderBy('sort');
    }

    /**
     * 关联排课
     */
    public function schedules(): HasMany
    {
        return $this->hasMany(Schedule::class, 'course_id');
    }

    /**
     * 关联报名
     */
    public function enrollments(): HasMany
    {
        return $this->hasMany(Enrollment::class, 'course_id');
    }

    /**
     * 是否已发布
     */
    public function isPublished(): bool
    {
        return $this->status === CourseStatus::PUBLISHED;
    }
}
