<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $oldIds = ['D-001', 'D-002', 'D-003', 'D-004', 'D-005'];
        $existing = DB::table('discover_posts')
            ->whereNull('user_id')
            ->whereIn('demo_author_id', $oldIds)
            ->orderBy('id')
            ->get();

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

        $min = 100000;
        $max = 599999;
        $used = [];
        foreach (DB::table('discover_posts')->whereNull('user_id')->pluck('demo_author_id') as $v) {
            if (is_numeric($v) && (int) $v >= $min && (int) $v <= $max) {
                $used[(int) $v] = true;
            }
        }

        $assign = [];
        foreach ($existing as $row) {
            do {
                $id = random_int($min, $max);
            } while (isset($used[$id]));
            $used[$id] = true;
            $assign[$row->id] = (string) $id;
        }

        foreach ($assign as $postId => $newDemoId) {
            DB::table('discover_posts')->where('id', $postId)->update(['demo_author_id' => $newDemoId]);
        }
    }

    public function down(): void
    {
        // Revert not required; optional restore to D-001..D-005 could be added
    }
};
