<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Maestro\Core\Database\Seeders\UserSeeder;
use Maestro\Core\Models\UserTableState;
use Tests\Fixtures\AuthTestUser;
use Tests\TestCase;

final class UserTableStateApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_roundtrip_table_state(): void
    {
        $this->seed(UserSeeder::class);

        $user = AuthTestUser::query()->where('email', 'demo@example.com')->first();
        self::assertNotNull($user);

        $state = [
            'visibleColumns' => ['name', 'email'],
            'columnOrder' => ['name', 'email'],
            'globalSearch' => 'x',
            'filters' => [],
            'columnWidths' => [],
        ];

        $this->actingAs($user, 'web')
            ->putJson('/api/user/table-states/settings.users', ['state' => $state])
            ->assertOk();

        $this->actingAs($user, 'web')
            ->getJson('/api/user/table-states/settings.users')
            ->assertOk()
            ->assertJsonPath('state.visibleColumns', ['name', 'email']);

        $this->actingAs($user, 'web')
            ->deleteJson('/api/user/table-states/settings.users')
            ->assertOk();

        $this->actingAs($user, 'web')
            ->getJson('/api/user/table-states/settings.users')
            ->assertOk()
            ->assertJsonPath('state', null);

        self::assertSame(0, UserTableState::query()->where('user_id', $user->id)->count());
    }

    public function test_invalid_table_key_format_returns_404(): void
    {
        $this->seed(UserSeeder::class);

        $user = AuthTestUser::query()->where('email', 'demo@example.com')->first();
        self::assertNotNull($user);

        $tooLong = str_repeat('a', 129);
        $this->actingAs($user, 'web')
            ->getJson('/api/user/table-states/'.$tooLong)
            ->assertStatus(404);
    }

    public function test_module_style_table_key_is_accepted(): void
    {
        $this->seed(UserSeeder::class);

        $user = AuthTestUser::query()->where('email', 'demo@example.com')->first();
        self::assertNotNull($user);

        $this->actingAs($user, 'web')
            ->getJson('/api/user/table-states/customers.index')
            ->assertOk()
            ->assertJsonPath('state', null);
    }
}
