<?php

use App\Services\Customer\CustomerQualityService;
use App\Services\Customer\CustomerQualitySettingsNormalizer;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): 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 === null) {
            return;
        }

        $row = DB::table('business_settings')
            ->where($keyColumn, CustomerQualityService::SETTING_KEY)
            ->first();

        if (! $row) {
            return;
        }

        $settings = json_decode((string) $row->value, true);
        $settings = $this->repairSettingsPayload(is_array($settings) ? $settings : []);

        DB::table('business_settings')
            ->where($keyColumn, CustomerQualityService::SETTING_KEY)
            ->update(['value' => json_encode($settings, JSON_UNESCAPED_SLASHES)]);
    }

    public function repairSettingsPayload(array $settings, ?string $resetAt = null): array
    {
        $normalizer = new CustomerQualitySettingsNormalizer;
        $settings = $normalizer->normalizeSettingsLists($settings);
        $resetAt ??= now()->toDateTimeString();

        $settings['auto_sync_enabled'] = false;
        $settings['automatic_removal_enabled'] = false;
        $settings['lookalike_sync_enabled'] = false;

        foreach (array_keys(CustomerQualityService::AUDIENCE_NAMES) as $audienceKey) {
            data_set($settings, 'audiences.'.$audienceKey.'.status', [
                'state' => 'not_checked',
                'is_ready' => false,
                'safety_reset_at' => $resetAt,
            ]);
            data_set($settings, 'audiences.'.$audienceKey.'.status_checked_at', null);
        }

        return $settings;
    }

    public function down(): void
    {
        // Safety switches and repaired list values are intentionally not reverted.
    }
};
