<?php

declare(strict_types=1);

use Builder\Core\Foundation\Definition\Field;
use Builder\Core\Foundation\Registry;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

it('binds builder.seo in the container', function (): void {
    expect(app()->bound('builder.seo'))->toBeTrue();
});

it('seo macro creates a field with component FieldSeoInput', function (): void {
    $field = Field::seo();

    expect($field->toArray()['component'])->toBe('FieldSeoInput');
});

it('seo macro defaults field name to seo', function (): void {
    $field = Field::seo();

    expect($field->getName())->toBe('seo');
});

it('seo macro accepts a custom field name', function (): void {
    $field = Field::seo('seo_data');

    expect($field->getName())->toBe('seo_data');
});

it('seo macro sets fields meta from SeoField::getFields', function (): void {
    $field = Field::seo();
    $meta = $field->toArray();

    expect($meta)->toHaveKey('fields')
        ->and($meta['fields'])->toBeArray()
        ->and(collect($meta['fields'])->pluck('name')->all())->toContain('title', 'description', 'robots');
});

it('registers manage:seo permission', function (): void {
    $registry = app(Registry::class);

    expect($registry->getRegisteredPermissions())->toContain('manage:seo');
});

it('seo macro sets no_index_select meta to true', function (): void {
    $field = Field::seo();

    expect($field->getMeta('no_index_select', false))->toBeTrue();
});

it('registers the seoColumns blueprint macro', function (): void {
    expect(Blueprint::hasMacro('seoColumns'))->toBeTrue();
});

it('registers redirect permissions', function (): void {
    $registry = app(Registry::class);
    $permissions = $registry->getRegisteredPermissions();

    expect($permissions)
        ->toContain('read:redirects')
        ->toContain('create:redirects')
        ->toContain('update:redirects')
        ->toContain('delete:redirects');
});

it('registers the RedirectResource with redirects slug', function (): void {
    $registry = app(Registry::class);
    $definition = $registry->resolveBySlug('redirects');

    expect($definition)->not->toBeNull()
        ->and($definition->getSlug())->toBe('redirects');
});

it('registers the SEO menu item with two children', function (): void {
    $registry = app(Registry::class);
    $items = $registry->menuItems();
    $seoItem = collect($items)->first(fn ($item) => $item->getKey() === 'seo');

    expect($seoItem)->not->toBeNull()
        ->and($seoItem->getChildren())->toHaveCount(2);
});

it('seoColumns macro adds the three seo columns', function (): void {
    Schema::create('seo_macro_test', function (Blueprint $table): void {
        $table->id();
        $table->seoColumns();
    });

    $columns = Schema::getColumnListing('seo_macro_test');

    expect($columns)->toContain('seo_title', 'seo_description', 'seo_robots');

    Schema::drop('seo_macro_test');
});
