<?php

namespace Database\Seeders\Tenant;

use Illuminate\Database\Seeder;
use Mtc\MercuryDataModels\Setting;

class AutoTraderHubPreserveDescriptionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * "description" used to be a mandatory (always-exported) field and has now moved
     * to the optional whitelist. Tenants who already configured a non-empty include
     * whitelist never had the chance to select it, so without this they would silently
     * stop sending descriptions. Append it to preserve the previous behaviour. Idempotent.
     *
     * List settings store their value as JSON in value_text (see SpecifiedTypeCast), so
     * we read/write that column directly - SettingRepository::update() does not handle
     * list values correctly.
     *
     * @return void
     */
    public function run()
    {
        $setting = Setting::query()
            ->where('config_key', 'auto-trader-hub-exported-optional-fields')
            ->first();

        if (!$setting) {
            return;
        }

        $included = json_decode($setting->value_text ?? '', true);

        if (!is_array($included) || $included === [] || in_array('description', $included, true)) {
            return;
        }

        $included[] = 'description';

        $setting->value_text = json_encode($included);
        $setting->save();
    }
}
