<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Page;

class AssignContentPageParentsBasedOnSlugs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pages:fix-parent-assignment';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set up parent page assignment based on slug structure';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        Page::fixTree();
        Page::all()->each(fn (Page $page) => $this->assignParent($page));
        Page::fixTree();
    }

    private function assignParent(Page $page): void
    {
        $slug_parts = explode('/', $page->slug);
        $last_slug = array_pop($slug_parts);
        $page->update([
            'page_slug' => $last_slug,
            'parent_id' => empty($slug_parts) ? null : $this->determineParent($slug_parts)
        ]);
    }

    private function determineParent(array $slug_parts): ?int
    {
        return Page::query()
            ->where('slug', implode('/', $slug_parts))
            ->first()
            ?->id;
    }
}
