<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // The column never had a constraint, so pre-existing rows may point at deleted channels.
        $orphans = DB::table('article_publications')
            ->whereNotIn('platform_channel_id', DB::table('platform_channels')->select('id'));

        if (($count = $orphans->count()) > 0) {
            Log::warning("Deleting {$count} orphaned article_publications rows before adding the channel foreign key.");
            $orphans->delete();
        }

        Schema::table('article_publications', function (Blueprint $table) {
            $table->foreign('platform_channel_id')
                ->references('id')
                ->on('platform_channels')
                ->onDelete('cascade');
        });
    }

    public function down(): void
    {
        // Orphan rows deleted in up() are not restored.
        Schema::table('article_publications', function (Blueprint $table) {
            $table->dropForeign(['platform_channel_id']);
        });
    }
};
