-- ============================================================
-- CS2 Skin Tracker — populate skin_conditions (per-skin wear tiers)
-- Run against the skintracker database as the app role.
-- Idempotent: re-running only inserts rows that don't exist yet.
--
-- The five CS2 wear tiers have fixed global float boundaries, but a
-- skin only appears in the tiers its own float range reaches, and the
-- achievable float within a tier is the intersection of the skin's
-- range with the tier's range. So for each skin we insert one row per
-- OVERLAPPING tier, with min/max clamped to that intersection.
--
--   Factory New      0.00 – 0.07
--   Minimal Wear     0.07 – 0.15
--   Field-Tested     0.15 – 0.38
--   Well-Worn        0.38 – 0.45
--   Battle-Scarred   0.45 – 1.00
--
-- Skins with no float bounds (e.g. Vanilla knives) get no rows.
-- ============================================================

SET search_path = skintracker;

INSERT INTO skin_conditions (skin_id, condition, float_min, float_max)
SELECT
    s.id,
    t.name,
    GREATEST(s.float_min, t.lo) AS float_min,  -- clamp the tier to the skin's range
    LEAST(s.float_max, t.hi)    AS float_max
FROM skins s
CROSS JOIN (VALUES
    ('Factory New',    0.00, 0.07),
    ('Minimal Wear',   0.07, 0.15),
    ('Field-Tested',   0.15, 0.38),
    ('Well-Worn',      0.38, 0.45),
    ('Battle-Scarred', 0.45, 1.00)
) AS t(name, lo, hi)
WHERE s.float_min IS NOT NULL
  AND s.float_max IS NOT NULL
  AND s.float_min < t.hi            -- skin's range overlaps this tier...
  AND s.float_max > t.lo            -- ...(strict, so a skin starting exactly at a
                                    --    boundary doesn't get the tier below it)
  AND NOT EXISTS (                  -- idempotent: skip tiers already recorded
        SELECT 1
        FROM skin_conditions sc
        WHERE sc.skin_id = s.id
          AND sc.condition = t.name
  )
ORDER BY s.id, t.lo;

-- ------------------------------------------------------------
-- Sanity checks (optional)
-- ------------------------------------------------------------
-- Rows per condition:
-- SELECT condition, count(*) FROM skin_conditions GROUP BY condition ORDER BY min(float_min);
--
-- Spot-check a capped skin (e.g. an Asiimov) shows clamped FT bounds:
-- SELECT s.name, sc.condition, sc.float_min, sc.float_max
-- FROM skin_conditions sc JOIN skins s ON s.id = sc.skin_id
-- WHERE s.name ILIKE 'Asiimov' ORDER BY sc.float_min;
