<?php

namespace Tests\Feature;

use App\Models\PlatformAccount;
use App\Models\PlatformInstance;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class StoreCommunityIdMigrationTest extends TestCase
{
    use RefreshDatabase;

    private function runMigration(): void
    {
        $migration = require database_path('migrations/2024_01_01_000015_store_numeric_community_id_on_platform_channels.php');

        $migration->up();
    }

    private function restoreSlugColumn(): void
    {
        Schema::table('platform_channels', function (Blueprint $table) {
            $table->dropUnique('platform_channels_channel_id_unique');
        });

        Schema::table('platform_channels', function (Blueprint $table) {
            $table->string('channel_id')->change();
        });

        Schema::table('platform_channels', function (Blueprint $table) {
            $table->unique(['platform_instance_id', 'channel_id'], 'platform_channels_channel_id_unique');
        });
    }

    private function seedChannel(PlatformInstance $instance, string $slug): int
    {
        return DB::table('platform_channels')->insertGetId([
            'platform_instance_id' => $instance->id,
            'name' => $slug,
            'display_name' => ucfirst($slug),
            'channel_id' => $slug,
            'is_active' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function instanceWithAccount(): PlatformInstance
    {
        $instance = PlatformInstance::factory()->create(['url' => 'https://lemmy.test']);
        PlatformAccount::factory()->create(['instance_url' => 'https://lemmy.test', 'is_active' => true]);

        return $instance;
    }

    public function test_it_replaces_the_slug_with_the_resolved_community_id(): void
    {
        $this->restoreSlugColumn();
        DB::table('platform_channels')->delete();

        $instance = $this->instanceWithAccount();
        $id = $this->seedChannel($instance, 'news');

        Http::fake([
            '*/api/v3/user/login*' => Http::response(['jwt' => 'token']),
            '*/api/v3/community*' => Http::response(['community_view' => ['community' => ['id' => 8]]]),
        ]);

        $this->runMigration();

        $this->assertSame(8, (int) DB::table('platform_channels')->where('id', $id)->value('channel_id'));
        $this->assertSame('news', DB::table('platform_channels')->where('id', $id)->value('name'));
    }

    public function test_it_aborts_when_a_community_cannot_be_resolved(): void
    {
        $this->restoreSlugColumn();
        DB::table('platform_channels')->delete();

        $instance = $this->instanceWithAccount();
        $this->seedChannel($instance, 'gone');

        Http::fake([
            '*/api/v3/user/login*' => Http::response(['jwt' => 'token']),
            '*/api/v3/community*' => Http::response('not found', 404),
        ]);

        $this->expectException(\Exception::class);

        $this->runMigration();
    }

    public function test_it_aborts_when_the_instance_has_no_active_account(): void
    {
        $this->restoreSlugColumn();
        DB::table('platform_channels')->delete();

        $instance = PlatformInstance::factory()->create(['url' => 'https://no-account.test']);
        $this->seedChannel($instance, 'news');

        $this->expectException(\RuntimeException::class);

        $this->runMigration();
    }
}
