<?php

namespace Daylight\Core\Models\Translations;

use Daylight\Core\Models\Category;
use Daylight\Core\Modules\PageBuilder\Concerns\InteractsWithComponents;
use Daylight\Core\Modules\PageBuilder\Contracts\HasComponents;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class CategoryTranslation extends Model implements HasComponents
{
    use HasSlug;
    use InteractsWithComponents;

    protected $guarded = [];

    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug')
            ->extraScope(fn ($builder) => $builder->where('locale', $this->locale)->whereCategoryId($this->category_id));
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(daylightModel('category'));
    }

    public function nestedSlug(): Attribute
    {
        //        $this->loadMissing([
        //            'category.ancestorsAndSelf.translations' => function ($q) {
        //                $q->where('locale', app()->getLocale());
        //            },
        //        ]);

        return Attribute::make(
            get: function () {
                return $this->category->ancestorsAndSelf->reverse()->map(fn ($category) => $category->slug)->join('/');
            }
        );
    }
}
