<?php

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

/**
 * Belga retired its public RSS feed, so the provider switched to website
 * discovery against their public JSON API (see #115).
 *
 * System feeds are maintained by the platform, not the end user, so their
 * stored url/type are updated through migrations rather than the UI.
 *
 * Keyed on `provider`, never on the previous url: environments are at
 * different points in this feed's history (some on the dead RSS url, some
 * already on an earlier API url), and a url-keyed update would silently
 * match nothing on most of them.
 *
 * `feeds.url` is unique while `feeds.provider` is not, so a blanket update
 * across several belga rows would collide. CreateFeedAction looks feeds up by
 * url, so a config url change can leave a second belga row behind: adopt the
 * one already on the target url and deactivate the superseded ones.
 *
 * Superseded rows are deactivated rather than deleted — routes.feed_id
 * cascades on delete, so removing a feed would take its routing rules with it.
 */
return new class extends Migration
{
    public function up(): void
    {
        $url = config('feed.providers.belga.languages.en.url');

        if (! is_string($url) || $url === '') {
            return;
        }

        $keepId = DB::table('feeds')->where('provider', 'belga')->where('url', $url)->min('id')
            ?? DB::table('feeds')->where('provider', 'belga')->min('id');

        if ($keepId === null) {
            return;
        }

        DB::table('feeds')
            ->where('provider', 'belga')
            ->where('id', '!=', $keepId)
            ->update([
                'is_active' => false,
                'updated_at' => now(),
            ]);

        DB::table('feeds')
            ->where('id', $keepId)
            ->update([
                'type' => 'website',
                'url' => $url,
                'updated_at' => now(),
            ]);
    }

    public function down(): void
    {
        // No rollback: the previous RSS endpoint 404s, so restoring it would
        // only reinstate a feed that silently yields no articles.
    }
};
