<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Laravel\Scout\Searchable;

class Category extends Model
{
    use HasFactory, Searchable;

    protected $fillable = [
        'parent_id',
        'name_ar',
        'name_en',
        'slug',
        'description_ar',
        'description_en',
        'image',
        'icon',
        'status',
        'meta_title',
        'meta_description',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'parent_id' => 'integer',
        ];
    }

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

    public function parent(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children(): HasMany
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    /**
     * Get the indexable data array for the model.
     *
     * @return array<string, mixed>
     */
    public function toSearchableArray(): array
    {
        return [
            'id' => (int) $this->id,
            'name_ar' => (string) $this->name_ar,
            'name_en' => (string) $this->name_en,
            'description_ar' => $this->description_ar ?: '',
            'description_en' => $this->description_en ?: '',
            'slug' => $this->slug ?: '',
            'parent_id' => $this->parent_id ?: null,
        ];
    }

    /**
     * Get the Scout engine index name for the model.
     */
    public function searchableAs(): string
    {
        return 'categories_index';
    }

    /**
     * Get the Meilisearch settings for the model.
     *
     * @return array<string, mixed>
     */
    public function meilisearchSettings(): array
    {
        return [
            'searchableAttributes' => [
                'name_en',
                'name_ar',
                'description_en',
                'description_ar',
            ],
            'filterableAttributes' => [
                'parent_id',
            ],
            'displayedAttributes' => [
                'id',
                'name_en',
                'name_ar',
                'description_en',
                'description_ar',
                'slug',
                'parent_id',
            ],
        ];
    }
}
