-- Normalize catalog stats: base damage/defense per weapon/armor *family* only.
-- Apply 000010_weapons_secondary_normalize.sql next (weapon speed/crit by class only).
-- Apply 000011_armor_base_tighten.sql (armor bases + gear-check HP target).
-- Rarity spread (+40% Legendary vs Common at same ilvl) comes from runtime_config M(rarity), not from inflating DB bases.
-- Sync template rows in `gear` (catalog mirror + denormalized primary_stat at ilvl=1).

UPDATE public.runtime_config
SET payload = payload || jsonb_build_object(
    'ilvlPerLevelMultiplier', 1.10,
    'rarityMultiplierCommon', 1.00,
    'rarityMultiplierUncommon', 1.0877573,
    'rarityMultiplierRare', 1.1832160,
    'rarityMultiplierEpic', 1.2870518,
    'rarityMultiplierLegendary', 1.40
),
    updated_at = now()
WHERE id = true;

UPDATE public.weapons SET damage = CASE type
    WHEN 'daggers' THEN 3
    WHEN 'sword' THEN 7
    WHEN 'axe' THEN 12
END;

UPDATE public.armor SET defense = CASE type
    WHEN 'light' THEN 3
    WHEN 'medium' THEN 7
    WHEN 'heavy' THEN 14
END;

-- Denormalized primary at ilvl=1: round(base * M(rarity)) — same M as runtime_config / §6.4.2
UPDATE public.gear AS g
SET
    base_primary = w.damage,
    primary_stat = ROUND(w.damage * CASE w.rarity
        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
    END)::integer
FROM public.weapons AS w
WHERE g.slot = 'main_hand'
  AND g.name = w.name;

UPDATE public.gear AS g
SET
    base_primary = a.defense,
    primary_stat = ROUND(a.defense * CASE a.rarity
        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
    END)::integer
FROM public.armor AS a
WHERE g.slot = 'chest'
  AND g.name = a.name;

-- Extended-slot catalog: keep one base_primary per form; scale primary_stat by row rarity (same M).
UPDATE public.equipment_items AS e
SET
    base_primary = s.canon_base,
    primary_stat = ROUND(s.canon_base * CASE e.rarity
        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
    END)::integer
FROM (
    SELECT form_id, MIN(base_primary) AS canon_base
    FROM public.equipment_items
    GROUP BY form_id
) AS s
WHERE e.form_id = s.form_id;
