<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class AcademyLessonBlock extends Model
{
    use SoftDeletes;

    protected static function booted(): void
    {
        static::deleting(function (self $block): void {
            $block->comparisonResults()->get()->each(function (AcademyAiComparisonResult $result) use ($block): void {
                if ($block->isForceDeleting()) {
                    $result->forceDelete();

                    return;
                }

                $result->delete();
            });
        });
    }

    protected $fillable = [
        'lesson_id',
        'type',
        'title',
        'payload',
        'sort_order',
        'active',
    ];

    protected $casts = [
        'payload' => 'array',
        'sort_order' => 'integer',
        'active' => 'boolean',
    ];

    public function lesson(): BelongsTo
    {
        return $this->belongsTo(AcademyLesson::class, 'lesson_id');
    }

    public function comparisonResults(): HasMany
    {
        return $this->hasMany(AcademyAiComparisonResult::class, 'lesson_block_id')
            ->orderBy('sort_order')
            ->orderBy('id');
    }

    public function activeComparisonResults(): HasMany
    {
        return $this->comparisonResults()->where('active', true);
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('active', true);
    }

    public function scopeOrdered(Builder $query): Builder
    {
        return $query->orderBy('sort_order')->orderBy('id');
    }
}
