<?php

namespace Daylight\Core\Models;

use Daylight\Core\Models\Concerns\IsRelatable;
use Daylight\Core\Models\Contracts\Relatable;
use Daylight\Core\Models\Enums\DisplayType;
use Daylight\Core\Modules\MediaLibrary\Contracts\HasMedia;
use Daylight\Core\Modules\MediaLibrary\Models\Concerns\InteractsWithMedia;
use Daylight\Core\Modules\MediaLibrary\Models\Media;
use Daylight\Core\Modules\MediaLibrary\Models\Pivot\Attachable;
use Daylight\Core\Modules\Multilingualism\Contracts\HasTranslations;
use Daylight\Core\Modules\Multilingualism\Models\Concerns\InteractsWithTranslations;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Support\Collection;
use Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;

class Category extends Model implements HasMedia, HasTranslations, Relatable
{
    use HasRecursiveRelationships;
    use InteractsWithMedia;
    use InteractsWithTranslations;
    use IsRelatable;

    protected $guarded = [];

    protected $casts = [
        'display' => DisplayType::class,
        'manual_sorting' => 'boolean',
    ];

    protected static function boot(): void
    {
        parent::boot();

        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('order');
        });
    }

    protected static function booted(): void
    {
        // Update nested slugs when category hierarchy changes
        static::saved(function (Category $category) {
            if ($category->wasChanged('parent_id')) {
                $category->load('translations');
                foreach ($category->translations as $translation) {
                    $translation->updateNestedSlug();
                    $translation->saveQuietly();
                    $translation->updateDescendantNestedSlugs();
                }
            }
        });
    }

    public function translatedFields(): array
    {
        return ['name', 'slug', 'meta_title', 'meta_description', 'robots'];
    }

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

    public function childrenRecursive(): HasMany
    {
        return $this->hasMany(daylightModel('category'), 'parent_id')->with('childrenRecursive');
    }

    public function attributes(): BelongsToMany
    {
        return $this->belongsToMany(daylightModel('attribute'));
    }

    public function products(): BelongsToMany
    {
        return $this->belongsToMany(daylightModel('product'));
    }

    public function translations(): HasMany
    {
        return $this->hasMany(daylightModel('category_translation'));
    }

    public function defaultTranslation(): HasOne
    {
        return $this->hasOne(daylightModel('category_translation'))
            ->where('locale', config('multilingualism.default_locale'));
    }

    // Override IsRelatable trait for translatable model
    public static function searchForRelation(string $query, array $excludeIds = [], int $limit = 10): Collection
    {
        $queryBuilder = static::query();

        if (! empty($excludeIds)) {
            $queryBuilder->whereNotIn('id', $excludeIds);
        }

        // Search in translations
        $queryBuilder->whereHas('translations', function ($q) use ($query) {
            $q->where('name', 'LIKE', "%{$query}%");
        });

        return $queryBuilder->limit($limit)
            ->get()
            ->map(fn ($item) => $item->formatForRelation());
    }

    public function formatForRelation(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'type' => 'Category',
        ];
    }

    public function gallery(): MorphToMany
    {
        return $this->morphToMany(Media::class, 'attachable')
            ->withPivot('properties', 'order')
            ->whereJsonContains('attachables.properties->field', 'image')
            ->using(Attachable::class)
            ->orderBy('order')
            ->withTimestamps();
    }
}
