<?php

namespace Daylight\Core\Models\Translations;

use Daylight\Core\Models\Page;
use Daylight\Core\Modules\PageBuilder\Concerns\InteractsWithComponents;
use Daylight\Core\Modules\PageBuilder\Contracts\HasComponents;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PageTranslation extends Model implements HasComponents
{
    use InteractsWithComponents;

    protected $guarded = [];

    protected static function booted(): void
    {
        static::saving(function (PageTranslation $translation) {
            if ($translation->isDirty('slug') || $translation->doesntExist()) {
                $translation->updateNestedSlug();
            }
        });

        static::saved(function (PageTranslation $translation) {
            if ($translation->wasRecentlyCreated && ! $translation->nested_slug) {
                $translation->updateNestedSlug();
                $translation->saveQuietly();
            }

            $translation->updateDescendantNestedSlugs();
        });
    }

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

    /**
     * Update the nested_slug for this translation based on ancestor slugs.
     */
    public function updateNestedSlug(): void
    {
        $page = $this->page()->with('ancestorsAndSelf.translations')->first();

        $this->nested_slug = $page->ancestorsAndSelf
            ->reverse()
            ->map(function ($ancestor) use ($page) {
                if ($ancestor->id === $page->id) {
                    return $this->slug;
                }

                return $ancestor->translations
                    ->where('locale', $this->locale)
                    ->first()?->slug;
            })
            ->filter()
            ->join('/');
    }

    /**
     * Update nested_slug for all descendant page translations.
     */
    public function updateDescendantNestedSlugs(): void
    {
        $page = $this->page;

        $descendants = Page::query()
            ->where('parent_id', $page->id)
            ->orWhereHas('ancestors', fn ($q) => $q->where('id', $page->id))
            ->with('translations')
            ->get();

        foreach ($descendants as $descendant) {
            foreach ($descendant->translations->where('locale', $this->locale) as $translation) {
                $translation->updateNestedSlug();
                $translation->saveQuietly();
            }
        }
    }
}
