<?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
    {
        Schema::table('notification_messages', function (Blueprint $table) {
            $table->foreignId('tenant_id')->nullable()->change();
        });
        Schema::table('user_notifications', function (Blueprint $table) {
            $table->foreignId('tenant_id')->nullable()->change();
        });

        Schema::create('system_notification_campaigns', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->string('title');
            $table->text('body');
            $table->string('action_url')->nullable();
            $table->string('icon')->default('cil-bell');
            $table->json('audience');
            $table->string('status', 30)->default('queued');
            $table->unsignedInteger('estimated_recipients')->default(0);
            $table->unsignedInteger('processed_recipients')->default(0);
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();
            $table->index(['tenant_id', 'status', 'created_at']);
        });

        Schema::table('user_notifications', function (Blueprint $table) {
            $table->foreignId('system_notification_campaign_id')->nullable()
                ->after('notification_message_id')->constrained()->cascadeOnDelete();
            $table->unique(['system_notification_campaign_id', 'user_id'], 'user_notifications_campaign_user_unique');
        });
    }

    public function down(): void
    {
        Schema::table('user_notifications', function (Blueprint $table) {
            $table->dropUnique('user_notifications_campaign_user_unique');
            $table->dropConstrainedForeignId('system_notification_campaign_id');
        });
        Schema::dropIfExists('system_notification_campaigns');
        Schema::table('user_notifications', fn (Blueprint $table) => $table->foreignId('tenant_id')->nullable(false)->change());
        Schema::table('notification_messages', fn (Blueprint $table) => $table->foreignId('tenant_id')->nullable(false)->change());
    }
};
