<?php

use App\Models\PlatformAccount;
use App\Modules\Lemmy\Services\LemmyApiService;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * channel_id held a community slug, resolved to Lemmy's numeric id on every
 * publish and every sync. It now holds that id directly; `name` remains the slug.
 */
return new class extends Migration
{
    public function up(): void
    {
        // Every id is resolved before any DDL runs: these lookups hit the live
        // instance and MariaDB will not roll back a schema change if one fails.
        $resolved = DB::table('platform_channels')
            ->orderBy('id')
            ->get()
            ->mapWithKeys(fn (object $channel) => [$channel->id => $this->resolve($channel)]);

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

        Schema::table('platform_channels', function (Blueprint $table) {
            $table->unsignedBigInteger('remote_community_id')->nullable()->after('channel_id');
        });

        foreach ($resolved as $id => $communityId) {
            DB::table('platform_channels')
                ->where('id', $id)
                ->update(['remote_community_id' => $communityId]);
        }

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

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

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

    public function down(): 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();
        });

        DB::table('platform_channels')->update(['channel_id' => DB::raw('name')]);

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

    private function resolve(object $channel): int
    {
        if (is_numeric($channel->channel_id)) {
            return (int) $channel->channel_id;
        }

        $instance = DB::table('platform_instances')->find($channel->platform_instance_id);

        if (! $instance) {
            throw new RuntimeException("Channel {$channel->id} has no platform instance; cannot resolve its community id.");
        }

        $account = PlatformAccount::where('instance_url', $instance->url)
            ->where('is_active', true)
            ->first();

        if (! $account) {
            throw new RuntimeException("No active account for {$instance->url}; cannot resolve community '{$channel->channel_id}'.");
        }

        $api = new LemmyApiService($instance->url);
        $token = $api->login($account->username, $account->password);

        if (! $token) {
            throw new RuntimeException("Could not authenticate against {$instance->url} to resolve community '{$channel->channel_id}'.");
        }

        return $api->getCommunityId($channel->channel_id, $token);
    }
};
