<?php

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

class AlterConversationsMessagesForPolymorphicParticipants extends Migration
{
    public function up()
    {
        Schema::table('conversations', function (Blueprint $table) {
            // Drop FKs if exist (safe guards)
            try { $table->dropForeign(['participant1_id']); } catch (\Throwable $e) {}
            try { $table->dropForeign(['participant2_id']); } catch (\Throwable $e) {}

            // Add participant types
            if (!Schema::hasColumn('conversations', 'participant1_type')) {
                $table->string('participant1_type', 20)->default('user')->after('participant1_id');
            }
            if (!Schema::hasColumn('conversations', 'participant2_type')) {
                $table->string('participant2_type', 20)->default('user')->after('participant2_id');
            }

            // Helpful composite index for uniqueness lookups
            $table->index(['participant1_type','participant1_id','participant2_type','participant2_id'], 'conv_participants_idx');
        });

        Schema::table('messages', function (Blueprint $table) {
            // Drop FKs if exist (safe guards)
            try { $table->dropForeign(['sender_id']); } catch (\Throwable $e) {}
            try { $table->dropForeign(['receiver_id']); } catch (\Throwable $e) {}

            if (!Schema::hasColumn('messages', 'sender_type')) {
                $table->string('sender_type', 20)->default('user')->after('sender_id');
            }
            if (!Schema::hasColumn('messages', 'receiver_type')) {
                $table->string('receiver_type', 20)->default('user')->after('receiver_id');
            }

            $table->index(['sender_type','sender_id']);
            $table->index(['receiver_type','receiver_id']);
        });
    }

    public function down()
    {
        Schema::table('messages', function (Blueprint $table) {
            if (Schema::hasColumn('messages', 'sender_type')) {
                $table->dropColumn('sender_type');
            }
            if (Schema::hasColumn('messages', 'receiver_type')) {
                $table->dropColumn('receiver_type');
            }
        });

        Schema::table('conversations', function (Blueprint $table) {
            if (Schema::hasColumn('conversations', 'participant1_type')) {
                $table->dropColumn('participant1_type');
            }
            if (Schema::hasColumn('conversations', 'participant2_type')) {
                $table->dropColumn('participant2_type');
            }
            try { $table->dropIndex('conv_participants_idx'); } catch (\Throwable $e) {}
        });
    }
}


