<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Feeds table
        Schema::create('feeds', function (Blueprint $table) {
            $table->id();
            $table->string('name'); // "VRT News", "Belga News Agency"
            $table->string('url'); // "https://vrt.be" or "https://feeds.example.com/rss.xml"
            $table->enum('type', ['website', 'rss']); // Feed type
            $table->string('provider'); // Feed provider code (vrt, belga, etc.)
            $table->foreignId('language_id')->nullable()->constrained();
            $table->text('description')->nullable();
            $table->json('settings')->nullable(); // Custom settings per feed type
            $table->boolean('is_active')->default(true);
            $table->timestamp('last_fetched_at')->nullable();
            $table->timestamps();

            $table->unique('url');
        });

        // Routes table (pivot between feeds and platform channels)
        Schema::create('routes', function (Blueprint $table) {
            $table->foreignId('feed_id')->constrained()->onDelete('cascade');
            $table->foreignId('platform_channel_id')->constrained()->onDelete('cascade');
            $table->boolean('is_active')->default(true);
            $table->integer('priority')->default(0); // for ordering/priority
            $table->timestamps();

            $table->primary(['feed_id', 'platform_channel_id']);
        });

        // Keywords table
        Schema::create('keywords', function (Blueprint $table) {
            $table->id();
            $table->foreignId('feed_id')->constrained()->onDelete('cascade');
            $table->foreignId('platform_channel_id')->constrained()->onDelete('cascade');
            $table->string('keyword');
            $table->boolean('is_active')->default(true);
            $table->timestamps();

            $table->unique(['feed_id', 'platform_channel_id', 'keyword'], 'keywords_unique');
        });

        // Add foreign key constraint for articles.feed_id now that feeds table exists
        Schema::table('articles', function (Blueprint $table) {
            $table->foreign('feed_id')->references('id')->on('feeds')->onDelete('set null');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('keywords');
        Schema::dropIfExists('routes');
        Schema::dropIfExists('feeds');
    }
};
