<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('emotions') || ! Schema::hasColumn('emotions', 'tenant_id')) {
            return;
        }

        // Treat any emotions that aren't tied to a known tenant as global
        DB::table('emotions')
            ->whereNotExists(function ($query) {
                $query->selectRaw(1)
                    ->from('tenants')
                    ->whereColumn('tenants.id', 'emotions.tenant_id');
            })
            ->update(['tenant_id' => null]);
    }

    public function down(): void
    {
        // No-op: data-only normalization cannot be safely reverted
    }
};
