<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\Migrations;

use JTL\Plugin\Migration;
use JTL\Update\IMigration;
use Plugin\tnt_stabila_shop\src\Enums\PluginSettings;

/**
 * Class Migration20260728120000
 *  add alert quiet-hours settings
 *
 * @author sssr
 * @created Tue, 28 Jul 2026 12:00:00 +0100
 */
class Migration20260728120000 extends Migration implements IMigration
{
    protected $author      = 'sssr';
    protected $description = 'add alert quiet-hours settings';

    /** @var list<PluginSettings> */
    private const NEW_SETTINGS = [
        PluginSettings::ALERT_QUIET_FROM,
        PluginSettings::ALERT_QUIET_UNTIL,
    ];

    public function getAuthor(): ?string
    {
        return 'sssr';
    }

    public function getDescription(): string
    {
        return 'add alert quiet-hours settings';
    }

    /**
     * @inheritdoc
     */
    public function up(): void
    {
        // Insert each new default setting only when absent, so this is idempotent
        // on a fresh install (where the initial migration already seeds every
        // PluginSettings case) as well as on an existing install (where it does not).
        foreach (self::NEW_SETTINGS as $pluginSetting) {
            try {
                $setting = \json_decode(
                    $pluginSetting->value,
                    false,
                    512,
                    JSON_THROW_ON_ERROR
                );
            } catch (\JsonException) {
                continue;
            }
            /** @var object{name: string, type: string, defaultValue: string} $setting */
            $existing = $this->db->getSingleObject(
                'SELECT settingName FROM `stabila_shop_settings` WHERE settingName = :settingName',
                ['settingName' => $setting->name]
            );
            if ($existing !== null) {
                continue;
            }
            $this->db->insertRow(
                'stabila_shop_settings',
                (object)[
                    'settingType'  => $setting->type,
                    'settingName'  => $setting->name,
                    'settingValue' => $setting->defaultValue,
                ],
            );
        }
    }

    /**
     * @inheritdoc
     */
    public function down(): void
    {
        foreach (self::NEW_SETTINGS as $pluginSetting) {
            try {
                $setting = \json_decode($pluginSetting->value, false, 512, JSON_THROW_ON_ERROR);
            } catch (\JsonException) {
                continue;
            }
            /** @var object{name: string} $setting */
            $this->db->delete('stabila_shop_settings', 'settingName', $setting->name);
        }
    }
}
