<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

test('declarations table exists after migration', function () {
    expect(Schema::hasTable('declarations'))->toBeTrue();
    expect(Schema::hasTable('folders'))->toBeFalse();
});

test('declaration_invitations table exists after migration', function () {
    expect(Schema::hasTable('declaration_invitations'))->toBeTrue();
    expect(Schema::hasTable('folder_invitations'))->toBeFalse();
});

test('messages table has declaration_id column instead of folder_id', function () {
    expect(Schema::hasColumn('messages', 'declaration_id'))->toBeTrue();
    expect(Schema::hasColumn('messages', 'folder_id'))->toBeFalse();
});

test('declaration_invitations table has declaration_id column instead of folder_id', function () {
    expect(Schema::hasColumn('declaration_invitations', 'declaration_id'))->toBeTrue();
    expect(Schema::hasColumn('declaration_invitations', 'folder_id'))->toBeFalse();
});

test('composite index exists on messages declaration_id and created_at', function () {
    $indexes = collect(DB::select("PRAGMA index_list('messages')"));
    $indexColumns = $indexes->flatMap(function ($index) {
        return collect(DB::select("PRAGMA index_info('{$index->name}')"))
            ->pluck('name')
            ->all();
    });

    expect($indexColumns->contains('declaration_id'))->toBeTrue();
    expect($indexColumns->contains('created_at'))->toBeTrue();
});

test('migration is reversible and rollback restores folder tables', function () {
    // Rollback team_invitations (1) + member-to-worker rename (1) + foundation migrations (3) + polymorphic update + rename migration
    $this->artisan('migrate:rollback', ['--step' => 7]);

    expect(Schema::hasTable('folders'))->toBeTrue();
    expect(Schema::hasTable('declarations'))->toBeFalse();
    expect(Schema::hasTable('folder_invitations'))->toBeTrue();
    expect(Schema::hasTable('declaration_invitations'))->toBeFalse();
    expect(Schema::hasColumn('messages', 'folder_id'))->toBeTrue();
    expect(Schema::hasColumn('messages', 'declaration_id'))->toBeFalse();

    // Re-apply to leave DB in correct state for other tests
    $this->artisan('migrate');
});
