<?php

declare(strict_types=1);

namespace Tests\Feature;

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

final class DataTableAdminApiTest extends TestCase
{
    use RefreshDatabase;

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

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

        UserTableState::query()->create([
            'user_id' => $admin->id,
            'table_key' => 'settings.users',
            'state' => ['visibleColumns' => ['email']],
        ]);

        $this->actingAs($admin, 'web')
            ->putJson('/api/superadmin/datatable-column-defaults/users', [
                'visibleKeys' => ['email', 'name', 'is_active'],
            ])
            ->assertOk();

        self::assertSame(
            ['email', 'name', 'is_active'],
            DataTableColumnDefault::query()->where('resource_key', 'users')->first()?->visible_keys,
        );

        $this->actingAs($admin, 'web')
            ->postJson('/api/superadmin/user-table-state/reset', [
                'userId' => $admin->id,
                'tableKey' => 'settings.users',
            ])
            ->assertOk();

        self::assertFalse(
            UserTableState::query()
                ->where('user_id', $admin->id)
                ->where('table_key', 'settings.users')
                ->exists(),
        );

        $this->actingAs($admin, 'web')
            ->deleteJson('/api/superadmin/datatable-column-defaults/users')
            ->assertOk();

        self::assertFalse(
            DataTableColumnDefault::query()->where('resource_key', 'users')->exists(),
        );
    }

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

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

        DataTableColumnDefault::query()->create([
            'resource_key' => 'users',
            'visible_keys' => ['email', 'name'],
        ]);

        $response = $this->actingAs($admin, 'web')
            ->getJson('/api/datatables/users/columns');

        $response->assertOk();
        $cols = $response->json();
        self::assertIsArray($cols);
        $vis = array_values(array_filter(array_map(
            fn (array $c) => ($c['defaultVisible'] ?? false) ? $c['key'] : null,
            $cols,
        )));
        self::assertSame(['email', 'name'], array_slice($vis, 0, 2));
    }

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

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

        $response = $this->actingAs($admin, 'web')
            ->getJson('/api/superadmin/datatable-column-defaults');

        $response->assertOk();
        $users = collect($response->json('resources'))->firstWhere('resourceKey', 'users');
        self::assertIsArray($users);
        self::assertSame('settings.users', $users['tableKey'] ?? null);
    }
}
