<?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
    {
        if (Schema::hasTable('customer_quality_metrics')) {
            Schema::table('customer_quality_metrics', function (Blueprint $table) {
                if (! Schema::hasColumn('customer_quality_metrics', 'customer_email')) {
                    $table->string('customer_email')->nullable()->index()->after('phone_hash');
                }
                if (! Schema::hasColumn('customer_quality_metrics', 'phone_validation_reason')) {
                    $table->string('phone_validation_reason', 40)->nullable()->index()->after('customer_email');
                }
                if (! Schema::hasColumn('customer_quality_metrics', 'is_high_quality')) {
                    $table->boolean('is_high_quality')->default(false)->index()->after('quality_status');
                }
                if (! Schema::hasColumn('customer_quality_metrics', 'is_high_return')) {
                    $table->boolean('is_high_return')->default(false)->index()->after('is_high_quality');
                }
                if (! Schema::hasColumn('customer_quality_metrics', 'is_high_cancel')) {
                    $table->boolean('is_high_cancel')->default(false)->index()->after('is_high_return');
                }
                if (! Schema::hasColumn('customer_quality_metrics', 'classification_reasons')) {
                    $table->json('classification_reasons')->nullable()->after('is_high_cancel');
                }
                if (! Schema::hasColumn('customer_quality_metrics', 'internal_exclusion_evidence')) {
                    $table->json('internal_exclusion_evidence')->nullable()->after('internal_exclusion_reason');
                }
            });
        }

        $this->forceSafeSettings();
    }

    private function forceSafeSettings(): void
    {
        if (! Schema::hasTable('business_settings') || ! Schema::hasColumn('business_settings', 'value')) {
            return;
        }
        $keyColumn = Schema::hasColumn('business_settings', 'key') ? 'key' : (Schema::hasColumn('business_settings', 'type') ? 'type' : null);
        if (! $keyColumn) {
            return;
        }
        $row = DB::table('business_settings')->where($keyColumn, 'customer_quality_meta_sync')->first();
        if (! $row) {
            return;
        }
        $settings = json_decode((string) $row->value, true) ?: [];
        $settings['auto_sync_enabled'] = false;
        $settings['automatic_removal_enabled'] = false;
        $settings['lookalike_sync_enabled'] = false;
        $settings['max_removal_percentage'] = min(20, (float) ($settings['max_removal_percentage'] ?? 20));
        data_set($settings, 'audiences.high_receive_low_return.meta_audience_id', (string) data_get($settings, 'audiences.high_receive_low_return.meta_audience_id', '120252718996570404') ?: '120252718996570404');
        data_set($settings, 'audiences.high_return_blacklisted.meta_audience_id', (string) data_get($settings, 'audiences.high_return_blacklisted.meta_audience_id', '120252720839690404') ?: '120252720839690404');
        foreach (['high_receive_low_return', 'high_return_blacklisted'] as $audienceKey) {
            data_set($settings, 'audiences.' . $audienceKey . '.status', [
                'state' => 'not_checked',
                'is_ready' => false,
                'stale_status_cleared_at' => now()->toDateTimeString(),
            ]);
            data_set($settings, 'audiences.' . $audienceKey . '.status_checked_at', null);
        }
        DB::table('business_settings')->where($keyColumn, 'customer_quality_meta_sync')->update(['value' => json_encode($settings, JSON_UNESCAPED_SLASHES)]);
    }

    public function down(): void
    {
        // Safety settings are intentionally not re-enabled on rollback.
    }
};
