<?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
{
    public function up(): void
    {
        // Migrate existing article approval_status to route_articles
        $validatedArticles = DB::table('articles')
            ->whereIn('approval_status', ['approved', 'rejected'])
            ->whereNotNull('validated_at')
            ->get();

        foreach ($validatedArticles as $article) {
            $routes = DB::table('routes')
                ->where('feed_id', $article->feed_id)
                ->where('is_active', true)
                ->get();

            foreach ($routes as $route) {
                $exists = DB::table('route_articles')
                    ->where('feed_id', $route->feed_id)
                    ->where('platform_channel_id', $route->platform_channel_id)
                    ->where('article_id', $article->id)
                    ->exists();

                if ($exists) {
                    continue;
                }

                DB::table('route_articles')->insert([
                    'feed_id' => $route->feed_id,
                    'platform_channel_id' => $route->platform_channel_id,
                    'article_id' => $article->id,
                    'approval_status' => $article->approval_status,
                    'validated_at' => $article->validated_at,
                    'created_at' => $article->created_at,
                    'updated_at' => now(),
                ]);
            }
        }

        // Remove approval_status column from articles
        Schema::table('articles', function (Blueprint $table) {
            $table->dropIndex(['published_at', 'approval_status']);
            $table->dropColumn('approval_status');
        });
    }

    public function down(): void
    {
        Schema::table('articles', function (Blueprint $table) {
            $table->enum('approval_status', ['pending', 'approved', 'rejected'])->default('pending')->after('feed_id');
            $table->index(['published_at', 'approval_status']);
        });
    }
};
