-- Nerf weapon primaries (−15% base) and defense/mixed primaries (−30% base); recompute denormalized primary_stat (§6.4, same M(rarity) and tol as 000012).
-- Runtime: global enemy encounter stat multiplier + unequipped-hero multiplier (see tuning / BuildEnemyInstanceForLevel).

WITH adjusted AS (
    SELECT
        g.id,
        GREATEST(
            1,
            ROUND(
                g.base_primary::numeric * (
                    CASE
                        WHEN g.slot = 'main_hand' THEN 0.85
                        WHEN g.stat_type::text IN ('defense', 'mixed') THEN 0.70
                        ELSE 1.0
                    END
                )
            )::integer
        ) AS new_base
    FROM public.gear AS g
)
UPDATE public.gear AS g
SET
    base_primary = a.new_base,
    primary_stat = GREATEST(
        1,
        ROUND(
            a.new_base::numeric
                * POWER(1.1, GREATEST(0, g.ilvl - 1))
                * (CASE g.rarity::text
                    WHEN 'common' THEN 1.0
                    WHEN 'uncommon' THEN 1.0877573
                    WHEN 'rare' THEN 1.1832160
                    WHEN 'epic' THEN 1.2870518
                    WHEN 'legendary' THEN 1.40
                    ELSE 1.0
                END)
                * (0.92::numeric + (mod(g.id, 24)::numeric / 23.0) * 0.23)
        )::integer
    )
FROM adjusted AS a
WHERE g.id = a.id;

UPDATE public.runtime_config
SET
    payload = payload || jsonb_build_object(
        'enemyEncounterStatMultiplier', 1.2,
        'enemyStatMultiplierVsUnequippedHero', 0.75
    ),
    updated_at = now()
WHERE id = true;
