<?php

declare(strict_types=1);

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    $legacyDatabasePath = base_path('test-results/legacy-password-export.sqlite');
    $legacyDirectory = dirname($legacyDatabasePath);

    if (! is_dir($legacyDirectory)) {
        mkdir($legacyDirectory, 0777, true);
    }

    @unlink($legacyDatabasePath);
    touch($legacyDatabasePath);

    config()->set('database.connections.legacy', [
        'driver' => 'sqlite',
        'database' => $legacyDatabasePath,
        'prefix' => '',
        'foreign_key_constraints' => false,
    ]);

    DB::purge('legacy');

    Schema::connection('legacy')->create('users', function (Blueprint $table): void {
        $table->unsignedBigInteger('user_id')->primary();
        $table->string('password2')->nullable();
        $table->string('password')->nullable();
        $table->unsignedTinyInteger('should_migrate')->default(0);
    });
});

afterEach(function (): void {
    Schema::connection('legacy')->dropIfExists('users');

    $legacyDatabasePath = base_path('test-results/legacy-password-export.sqlite');
    @unlink($legacyDatabasePath);

    $sqlPath = base_path('test-results/export-legacy-passwords.sql');
    @unlink($sqlPath);
});

it('exports only legacy users flagged with should_migrate=1', function (): void {
    DB::connection('legacy')->table('users')->insert([
        [
            'user_id' => 101,
            'password2' => '$2y$12$abcdefghijklmnopqrstuvABCDEFGHIJKLMNOpqrstuvwxyz12345',
            'password' => null,
            'should_migrate' => 1,
        ],
        [
            'user_id' => 102,
            'password2' => '$2y$12$zzzzzzzzzzzzzzzzzzzzzzABCDEFGHIJKLMNOpqrstuvwxyz12345',
            'password' => null,
            'should_migrate' => 0,
        ],
        [
            'user_id' => 103,
            'password2' => 'abc123',
            'password' => null,
            'should_migrate' => 1,
        ],
    ]);

    $sqlPath = base_path('test-results/export-legacy-passwords.sql');

    $code = Artisan::call('skinbase:export-legacy-passwords', [
        '--sql' => $sqlPath,
        '--chunk' => 1,
    ]);

    $output = Artisan::output();
    $sql = file_get_contents($sqlPath);

    expect($code)->toBe(0)
        ->and($output)->toContain('Wrote 1 rows to: ' . $sqlPath)
        ->and($sql)->not->toBeFalse()
        ->and($sql)->toContain('user_id=101')
        ->and($sql)->not->toContain('user_id=102')
        ->and($sql)->not->toContain('user_id=103')
        ->and($sql)->toContain('-- Exported: 1 user(s)');
});