<?php

namespace Modules\Dummy\Database\Seeders\Modules\Subscription\versions\v7_5_0;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PreferenceTableSeeder extends Seeder
{
    private const DEPRECATED_IMAGE_MODELS = [
        'dall-e-2',
        'dall-e-3',
    ];

    private const REPLACEMENT_MODEL = 'gpt-image-1';

    private const SUPPORTED_IMAGE_MODELS = [
        'gpt-image-1',
        'gpt-image-1.5',
        'gpt-image-1-mini',
        'gpt-image-2',
    ];

    /**
     * Remove deprecated DALL-E models from image provider preferences.
     */
    public function run(): void
    {
        DB::transaction(function () {
            $rows = DB::table('preferences')
                ->whereIn('category', ['imagemaker', 'aisocialsuitesimage'])
                ->get();

            foreach ($rows as $row) {
                $value = json_decode($row->value, true);
                if (! is_array($value)) {
                    continue;
                }

                $updated = false;
                foreach ($value as $index => $item) {
                    if (! is_array($item)) {
                        continue;
                    }

                    if (($item['name'] ?? '') === 'model' && ($item['type'] ?? '') === 'dropdown') {
                        $models = isset($item['value']) && is_array($item['value']) ? $item['value'] : [];
                        $hadDeprecated = (bool) array_intersect($models, self::DEPRECATED_IMAGE_MODELS);
                        $filteredModels = array_values(array_diff($models, self::DEPRECATED_IMAGE_MODELS));

                        if ($hadDeprecated || $filteredModels === []) {
                            $value[$index]['value'] = self::SUPPORTED_IMAGE_MODELS;
                            $updated = true;
                        }

                        if (isset($value[$index]['default_value'])
                            && in_array($value[$index]['default_value'], self::DEPRECATED_IMAGE_MODELS, true)
                        ) {
                            $value[$index]['default_value'] = self::REPLACEMENT_MODEL;
                            $updated = true;
                        }

                        break;
                    }
                }

                if ($updated) {
                    DB::table('preferences')
                        ->where('id', $row->id)
                        ->update(['value' => json_encode($value)]);
                }
            }

            DB::table('preferences')
                ->where('field', 'openai_engine')
                ->whereIn('value', self::DEPRECATED_IMAGE_MODELS)
                ->update(['value' => self::REPLACEMENT_MODEL]);
        });
    }
}
