<?php

declare(strict_types=1);

namespace Builder\Seo\Tests;

use Builder\Core\BuilderServiceProvider;
use Builder\Core\Foundation\Concerns\HasBuilderAccess;
use Builder\Core\Foundation\Contracts\BuilderAccessible;
use Builder\Seo\SeoServiceProvider;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Inertia\ServiceProvider as InertiaServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;
use Spatie\LaravelSettings\LaravelSettingsServiceProvider;
use Spatie\Permission\PermissionServiceProvider;

abstract class TestCase extends OrchestraTestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        $hotDir = $this->app->publicPath('vendor/builder/core');

        if (! is_dir($hotDir) && ! @mkdir($hotDir, 0755, true) && ! is_dir($hotDir)) {
            throw new \RuntimeException("Unable to create directory: {$hotDir}");
        }

        file_put_contents($hotDir.'/hot', 'http://localhost:5173');

        config([
            'inertia.pages.paths' => array_merge(
                config('inertia.pages.paths', []),
                [
                    __DIR__.'/../vendor/builder/core/resources/js/Pages',
                ],
            ),
        ]);
    }

    protected function getPackageProviders($app): array
    {
        return [
            InertiaServiceProvider::class,
            PermissionServiceProvider::class,
            LaravelSettingsServiceProvider::class,
            SeoServiceProvider::class,
            BuilderServiceProvider::class,
        ];
    }

    public function getEnvironmentSetUp($app): void
    {
        config()->set('app.key', 'base64:'.base64_encode(str_repeat('A', 32)));
        config()->set('database.default', 'testing');
        config()->set('database.connections.testing', [
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
            'foreign_key_constraints' => true,
        ]);
        config()->set('auth.guards.web.provider', 'users');
        config()->set('auth.providers.users.driver', 'eloquent');
        config()->set('auth.providers.users.model', SeoTestUser::class);

        $app['db']->connection()->getSchemaBuilder()->create('users', function (Blueprint $table): void {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->json('widget_preferences')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }
}

/**
 * Minimal test user with all SEO permissions.
 */
final class SeoTestUser extends Authenticatable implements BuilderAccessible
{
    use HasBuilderAccess;

    protected $table = 'users';

    protected $guarded = [];

    public function builderPermissions(): array
    {
        return ['*'];
    }
}
