<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * channel_id is used verbatim as the Lemmy community slug at publish time
     * (LemmyPublisher -> getCommunityId). It is kept equal to `name` on create,
     * but only `name` had a uniqueness guarantee. Enforce the same scope on
     * channel_id so duplicate/ambiguous community references cannot exist.
     */
    public function up(): void
    {
        $this->guardAgainstDuplicates();

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

    /**
     * Pre-flight check so an existing database with drifted data fails with an
     * actionable message naming the offending rows, rather than a raw driver error.
     */
    private function guardAgainstDuplicates(): void
    {
        $duplicates = DB::table('platform_channels')
            ->select('platform_instance_id', 'channel_id', DB::raw('COUNT(*) as total'))
            ->groupBy('platform_instance_id', 'channel_id')
            ->havingRaw('COUNT(*) > 1')
            ->get();

        if ($duplicates->isEmpty()) {
            return;
        }

        $details = $duplicates
            ->map(fn ($row) => "platform_instance_id={$row->platform_instance_id} channel_id='{$row->channel_id}' ({$row->total} rows)")
            ->implode('; ');

        throw new RuntimeException(
            'Cannot add unique index on platform_channels (platform_instance_id, channel_id): '.
            'duplicate rows exist. Resolve these before migrating: '.$details
        );
    }

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