<?php

declare(strict_types=1);

use Builder\Core\Foundation\Definition\JsModule;
use Builder\Core\Foundation\Registry;
use Builder\Core\Tests\BuilderTestUser;
use Illuminate\Support\Facades\Schema;

beforeEach(function (): void {
    Schema::create('users', function ($table): void {
        $table->id();
        $table->string('name')->nullable();
        $table->string('email')->nullable();
        $table->string('password')->nullable();
        $table->timestamps();
    });

    config(['auth.providers.users.model' => BuilderTestUser::class]);
});

it('GET /module-manifest returns JSON with modules array', function (): void {
    $user = BuilderTestUser::create(['name' => 'Admin', 'email' => 'admin@test.com', 'password' => 'x']);

    $this->actingAs($user)
        ->get(route('builder.modules.manifest'))
        ->assertOk()
        ->assertJsonStructure(['modules']);
});

it('GET /module-manifest excludes modules without a publicPath', function (): void {
    $module = JsModule::make()->setKey('no-path-module')->setLabel('No Path');
    app(Registry::class)->register($module);

    $user = BuilderTestUser::create(['name' => 'Admin', 'email' => 'admin@test.com', 'password' => 'x']);

    $response = $this->actingAs($user)
        ->get(route('builder.modules.manifest'))
        ->assertOk();

    $keys = array_column($response->json()['modules'], 'key');
    expect($keys)->not->toContain('no-path-module');
});

it('GET /module-manifest includes registered modules', function (): void {
    // Create the hot file so Assets::entryUrl() uses the dev-server path instead of manifest.
    $moduleDir = public_path('vendor/builder/test-module');
    if (! is_dir($moduleDir)) {
        mkdir($moduleDir, 0755, true);
    }
    file_put_contents($moduleDir.'/hot', 'http://localhost:5174');

    $module = JsModule::make()->setKey('test-module')->setLabel('Test JsModule')->setPublicPath($moduleDir);
    app(Registry::class)->register($module);

    $user = BuilderTestUser::create(['name' => 'Admin', 'email' => 'admin@test.com', 'password' => 'x']);

    $response = $this->actingAs($user)
        ->get(route('builder.modules.manifest'))
        ->assertOk();

    $json = $response->json();

    $keys = array_column($json['modules'], 'key');
    expect($keys)->toContain('test-module');
});
