<?php

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

/**
 * The Belga API offset parameter is 0-based, so the previous url's offset=1
 * silently skipped the newest press release on every fetch (#158). The url in
 * config/feed.php moved to offset=0; this migration updates the stored feed
 * row to match.
 *
 * System feeds are maintained by the platform, not the end user, so their
 * stored url is updated through migrations rather than the UI.
 *
 * Keyed on `provider`, never on the previous url: CreateFeedAction looks feeds
 * up by url via firstOrCreate, so leaving the row on the old url while config
 * points elsewhere would insert a second belga row on the next seed instead of
 * updating the existing one.
 *
 * `feeds.url` is unique while `feeds.provider` is not, so a blanket update
 * across several belga rows would collide. Adopt the row already on the target
 * url (or the oldest belga row when none is) and deactivate the rest.
 *
 * 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([
                'url' => $url,
                'updated_at' => now(),
            ]);
    }

    public function down(): void
    {
        // No rollback: restoring offset=1 would reinstate a feed that silently
        // drops the newest press release.
    }
};
