<?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\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class AcademyPromptTemplate extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'category_id',
        'title',
        'slug',
        'excerpt',
        'prompt',
        'negative_prompt',
        'usage_notes',
        'workflow_notes',
        'documentation',
        'placeholders',
        'helper_prompts',
        'prompt_variants',
        'difficulty',
        'access_level',
        'aspect_ratio',
        'tags',
        'tool_notes',
        'preview_image',
        'featured',
        'prompt_of_week',
        'active',
        'published_at',
        'seo_title',
        'seo_description',
    ];

    protected $casts = [
        'tags' => 'array',
        'tool_notes' => 'array',
        'documentation' => 'array',
        'placeholders' => 'array',
        'helper_prompts' => 'array',
        'prompt_variants' => 'array',
        'featured' => 'boolean',
        'prompt_of_week' => 'boolean',
        'active' => 'boolean',
        'published_at' => 'datetime',
    ];

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

    public function scopePublished(Builder $query): Builder
    {
        return $query->whereNotNull('published_at')->where('published_at', '<=', now());
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(AcademyCategory::class, 'category_id');
    }

    public function savedBy(): HasMany
    {
        return $this->hasMany(AcademySavedPrompt::class, 'prompt_template_id');
    }

    public function packs(): BelongsToMany
    {
        return $this->belongsToMany(AcademyPromptPack::class, 'academy_prompt_pack_items', 'prompt_template_id', 'pack_id')
            ->withPivot('order_num')
            ->withTimestamps();
    }
}