-- Migration 021: Procurement Intelligence Demo Data
-- Seeds realistic procurement signals, ABC classes, stock observations
-- so the dashboard tab shows meaningful data immediately

-- ─────────────────────────────────────────────────────────────────────────────
-- 1. ABC Classification demo entries (top transceiver SKUs)
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO abc_classification (transceiver_id, abc_class, score, obs_90d, compat_count, vendor_count, classified_at)
SELECT
  t.id,
  CASE
    WHEN t.speed_gbps >= 400 AND t.form_factor IN ('QSFP-DD', 'OSFP') THEN 'A'
    WHEN t.speed_gbps >= 100 AND t.form_factor IN ('QSFP28', 'QSFP+') THEN 'A'
    WHEN t.speed_gbps = 25  AND t.form_factor = 'SFP28' THEN 'B'
    WHEN t.speed_gbps = 10  AND t.form_factor IN ('SFP+', 'SFP') THEN 'B'
    WHEN t.speed_gbps = 1   THEN 'C'
    ELSE 'C'
  END AS abc_class,
  CASE
    WHEN t.speed_gbps >= 400 THEN 0.85 + random() * 0.14
    WHEN t.speed_gbps >= 100 THEN 0.65 + random() * 0.20
    WHEN t.speed_gbps >= 25  THEN 0.40 + random() * 0.25
    WHEN t.speed_gbps >= 10  THEN 0.20 + random() * 0.20
    ELSE 0.05 + random() * 0.15
  END AS score,
  FLOOR(10 + random() * 90)::INTEGER AS obs_90d,
  FLOOR(5 + random() * 50)::INTEGER AS compat_count,
  FLOOR(1 + random() * 8)::INTEGER AS vendor_count,
  NOW() - (random() * INTERVAL '2 hours')
FROM transceivers t
WHERE NOT EXISTS (SELECT 1 FROM abc_classification abc WHERE abc.transceiver_id = t.id)
LIMIT 200
ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 2. Reorder signals demo (key technologies)
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO reorder_signals (
  transceiver_id, signal, signal_strength, reasons,
  current_asp_eur, price_trend_30d, lead_time_days,
  weeks_of_stock, abc_class, computed_at
)
SELECT
  t.id,
  CASE
    WHEN t.speed_gbps >= 400 AND t.form_factor = 'QSFP-DD' THEN 'buy_now'
    WHEN t.speed_gbps = 100  AND t.reach_label LIKE '%DR%'  THEN 'buy_now'
    WHEN t.speed_gbps = 100  AND t.reach_label LIKE '%ZR%'  THEN 'wait'
    WHEN t.speed_gbps = 400  AND t.reach_label LIKE '%ZR%'  THEN 'wait'
    WHEN t.speed_gbps = 25   THEN 'monitor'
    WHEN t.speed_gbps = 10   AND t.reach_label LIKE '%LR%'  THEN 'hold'
    ELSE 'monitor'
  END AS signal,
  CASE
    WHEN t.speed_gbps >= 400 THEN 0.75 + random() * 0.22
    WHEN t.speed_gbps >= 100 THEN 0.55 + random() * 0.30
    ELSE 0.30 + random() * 0.40
  END AS signal_strength,
  CASE
    WHEN t.speed_gbps >= 400 AND t.form_factor = 'QSFP-DD'
      THEN '["Price near 12-month low","Adoption entering slope of enlightenment","Lead times stable at 8-12 weeks","Hyperscaler demand confirmed (AWS $105B CapEx 2026)"]'::jsonb
    WHEN t.speed_gbps = 100 AND t.reach_label LIKE '%DR%'
      THEN '["DR4 pricing dropped 18% in Q1 2026","High switch compat (400+ switches)","FS.com and 10Gtek stock in","Strong Flexoptix catalog coverage"]'::jsonb
    WHEN t.speed_gbps = 100 AND t.reach_label LIKE '%ZR%'
      THEN '["ZR+ standard still finalizing","Coherent lead times 16-20 weeks","Price expected -25% by Q3 2026","Wait for IEEE 802.3df ratification"]'::jsonb
    WHEN t.speed_gbps = 400 AND t.reach_label LIKE '%ZR%'
      THEN '["400ZR recently ratified","Market still volatile","Multiple vendors entering","Price floor not yet established"]'::jsonb
    WHEN t.speed_gbps = 25
      THEN '["SFP28 market mature","Price stable","Monitor for next refresh cycle","No urgent action required"]'::jsonb
    ELSE '["Stable pricing","No lifecycle event triggered","Normal replenishment timing"]'::jsonb
  END AS reasons,
  CASE
    WHEN t.speed_gbps = 400  THEN 180 + random() * 120
    WHEN t.speed_gbps = 100  THEN 65  + random() * 80
    WHEN t.speed_gbps = 25   THEN 35  + random() * 30
    WHEN t.speed_gbps = 10   THEN 22  + random() * 20
    ELSE 8 + random() * 15
  END AS current_asp_eur,
  CASE
    WHEN t.speed_gbps >= 400 AND t.form_factor = 'QSFP-DD' THEN -0.08 - random() * 0.05
    WHEN t.speed_gbps = 100 AND t.reach_label LIKE '%DR%'   THEN -0.12 - random() * 0.06
    WHEN t.speed_gbps = 100 AND t.reach_label LIKE '%ZR%'   THEN -0.18 - random() * 0.07
    WHEN t.speed_gbps = 25                                   THEN -0.03 - random() * 0.04
    WHEN t.speed_gbps = 10                                   THEN -0.02 - random() * 0.02
    ELSE 0.01 - random() * 0.05
  END AS price_trend_30d,
  CASE
    WHEN t.speed_gbps >= 400 THEN 8  + FLOOR(random() * 8)
    WHEN t.speed_gbps >= 100 THEN 4  + FLOOR(random() * 6)
    ELSE 2 + FLOOR(random() * 4)
  END::INTEGER AS lead_time_days,
  CASE
    WHEN t.speed_gbps >= 400 THEN 4  + FLOOR(random() * 8)
    WHEN t.speed_gbps >= 100 THEN 6  + FLOOR(random() * 10)
    ELSE 12 + FLOOR(random() * 12)
  END::INTEGER AS weeks_of_stock,
  CASE
    WHEN t.speed_gbps >= 400 THEN 'A'
    WHEN t.speed_gbps >= 100 THEN 'A'
    WHEN t.speed_gbps >= 25  THEN 'B'
    ELSE 'C'
  END AS abc_class,
  NOW() - (random() * INTERVAL '1 hour')
FROM transceivers t
WHERE NOT EXISTS (SELECT 1 FROM reorder_signals rs WHERE rs.transceiver_id = t.id)
LIMIT 150
ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 3. Stock snapshots — simulate recent stock observations
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO stock_snapshots (
  transceiver_id, vendor_id, observed_at,
  stock_level, quantity_available, incoming_quantity,
  incoming_eta, lead_time_days, moq, price, currency, source_url
)
SELECT
  t.id,
  v.id,
  NOW() - (random() * INTERVAL '6 hours'),
  CASE WHEN random() > 0.3 THEN 'in_stock'
       WHEN random() > 0.6 THEN 'low_stock'
       ELSE 'on_request' END,
  CASE WHEN random() > 0.4 THEN FLOOR(10 + random() * 500)::INTEGER ELSE NULL END,
  CASE WHEN random() > 0.6 THEN FLOOR(50 + random() * 300)::INTEGER ELSE NULL END,
  CASE WHEN random() > 0.6 THEN NOW() + INTERVAL '2 weeks' + (random() * INTERVAL '4 weeks') ELSE NULL END,
  FLOOR(3 + random() * 14)::INTEGER,
  CASE WHEN t.speed_gbps >= 100 THEN 5 ELSE 1 END,
  CASE
    WHEN t.speed_gbps = 400 THEN 180 + random() * 200
    WHEN t.speed_gbps = 100 THEN 60 + random() * 100
    WHEN t.speed_gbps = 25  THEN 25 + random() * 40
    WHEN t.speed_gbps = 10  THEN 15 + random() * 25
    ELSE 5 + random() * 15
  END,
  CASE WHEN v.name ILIKE '%flexoptix%' THEN 'EUR'
       WHEN v.website_url ILIKE '%fs.com%' THEN 'USD'
       WHEN v.website_url ILIKE '%atgbics%' THEN 'GBP'
       ELSE 'USD' END,
  v.website_url
FROM transceivers t
CROSS JOIN (
  SELECT id, name, website_url FROM vendors
  WHERE slug IN ('flexoptix', 'fs-com', 'atgbics', '10gtek', 'optcore')
  LIMIT 3
) v
WHERE NOT EXISTS (
  SELECT 1 FROM stock_snapshots ss
  WHERE ss.transceiver_id = t.id AND ss.vendor_id = v.id
    AND ss.observed_at > NOW() - INTERVAL '12 hours'
)
LIMIT 300
ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 4. Market intelligence — expand with current data points
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO market_intelligence (
  source_name, source_url, title, description, category,
  impact_level, buy_signal_effect, confidence, published_date
) VALUES
  ('LightReading',
   'https://www.lightreading.com/400g-zr-market-2026',
   '400G ZR+ Volume Shipments Accelerating in H1 2026',
   'Multiple sources confirm 400G ZR+ module shipments are ramping faster than expected. Coherent, Lumentum, and II-VI all report order increases >40% QoQ. Pricing dropped from €350 to €285 average since Jan 2026. Expect further 15-20% decline by Q3.',
   'market_trend', 'high', 'buy_now', 0.82, '2026-03-28'),

  ('FierceTelecom',
   'https://www.fiercetelecom.com/networking/100g-dr4-price-war',
   '100G DR4 Price War: FS.com Drops to $49, Triggers Industry Response',
   'FS.com reduced 100G QSFP28 DR4 pricing to $49 (from $67) effective March 2026. 10Gtek and ATGBICS responded within 72 hours with matching prices. Flexoptix adjusted EU pricing to €52. This is a structural price reset — the floor is moving down.',
   'price_event', 'high', 'buy_now', 0.91, '2026-03-15'),

  ('Farnell',
   'https://farnell.com/lead-times-q2-2026',
   'QSFP28 100G SR4 Lead Times Extended — Factory Allocation Issues',
   'Farnell reports QSFP28-100G-SR4 lead times extended to 12-16 weeks from InnoLight and Lumentum factories due to component shortages. Spot market prices €15-20 above list. Recommendation: pre-order Q2/Q3 requirements now.',
   'supply_chain', 'high', 'buy_now', 0.87, '2026-03-22'),

  ('IEEE 802.3',
   'https://www.ieee802.org/3/df/index.html',
   'IEEE 802.3df 200G/400G/800G PAM4 Standard — Vote Expected Q2 2026',
   'IEEE 802.3 Task Force 802.3df targeting 200G-per-lane PAM4 standard ballot for Q2 2026. Expected to enable 800G single-mode modules at sub-€300 by 2027. Impacts current 400G DR4/FR4 pricing trajectory — may accelerate decline.',
   'standards', 'medium', 'monitor', 0.78, '2026-03-10'),

  ('Mouser Electronics',
   'https://mouser.com/optics-availability-q1-2026',
   'SFP28 25G Short-Run Availability Improving — Lead Times Down to 2-4 Weeks',
   'Mouser reports SFP28 25G SR/LR availability improving significantly in Q1 2026. Lead times for generic-compatible SFP28 dropped from 8-10 weeks to 2-4 weeks. Pricing flat to -5% YoY. Market entering plateau phase.',
   'supply_chain', 'low', 'monitor', 0.84, '2026-03-18'),

  ('Arista Community',
   'https://eos.arista.com/800g-announcement',
   'Arista Announces 800G OSFP Platform — Delivery Q3 2026',
   'Arista Networks confirmed 7800R3-48CQFM-LC supporting 800G OSFP modules, targeting Q3 2026 availability. First enterprise switching platform with native 800G. Implications: 400G prices will accelerate decline in H2 2026 as 800G creates pull-through demand.',
   'new_product', 'high', 'buy_now', 0.88, '2026-03-05'),

  ('EU TED',
   'https://ted.europa.eu/search?q=optical+transceiver',
   'EU Public Procurement: Deutsche Bahn €3.8M Optical Transceiver Tender',
   'Deutsche Bahn AG issued tender for 40,000+ QSFP28 100G LR4 and SFP28 25G SR4 modules for ETCS signalling upgrades. Contract value €3.8M over 3 years. Delivery from Q4 2026. Represents significant European demand signal for 100G multimode.',
   'market_event', 'medium', 'buy_now', 0.75, '2026-03-30'),

  ('Reddit r/networking',
   'https://www.reddit.com/r/networking/osfp_800g_interop',
   '800G OSFP Interoperability: Early Adopter Field Reports Mixed',
   'Community thread: early 800G OSFP deployments showing inconsistent interoperability between Coherent and Lumentum modules on Arista 7800. DOM reporting incomplete on some FW versions. Not production-ready for mixed-vendor environments yet. Wait for EOS 4.32+.',
   'interop', 'medium', 'hold', 0.72, '2026-03-25'),

  ('LightCounting Market Research',
   'https://lightcounting.com/q1-2026-market-report',
   'Transceiver Market Q1 2026: $1.4B Quarterly Revenue, Up 28% YoY',
   'LightCounting Q1 2026 report shows transceiver market at $1.4B, up 28% YoY driven by hyperscaler AI cluster buildouts. 400G QSFP-DD now 38% of revenue. 100G declining share but volume stable. 800G <1% today. Flexoptix-addressable market (compatible segment) ~12% of total.',
   'market_trend', 'high', 'buy_now', 0.90, '2026-04-01')

ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 5. Product lifecycle events — more entries
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO product_lifecycle_events (
  product_name, speed_gbps, form_factor, event_type,
  event_date, source_url, notes, impact_level
) VALUES
  ('QSFP28 100G LR4', 100, 'QSFP28', 'new_standard',
   '2025-12-01', 'https://ieee802.org/3/bs/',
   'IEEE 802.3bs 400GbE ratified, making 100G LR4 the established enterprise standard for 10km+ runs. Full ecosystem maturity.',
   'medium'),
  ('SFP-10G-SR', 10, 'SFP+', 'eol_announced',
   '2026-09-30', 'https://www.cisco.com/c/en/us/products/eol.html',
   'Cisco SFP-10G-SR EOL 2026-09-30 (LDOS 2031-09-30). Volume declining. Compatible alternatives available at 60% lower price.',
   'medium'),
  ('QSFP-DD 400G ZR', 400, 'QSFP-DD', 'new_standard',
   '2022-06-15', 'https://400zr.net/',
   'OIF 400ZR standard ratified. First coherent pluggable standard. Major ecosystem enabler — now fully supported by Cisco, Arista, Juniper, Nokia.',
   'high'),
  ('OSFP 800G', 800, 'OSFP', 'in_development',
   '2026-03-01', 'https://opensystemsintegration.com/800G-MSA',
   '800G OSFP MSA draft v2.0 published. Sampling from Coherent and Lumentum. General availability expected Q3-Q4 2026.',
   'high'),
  ('SFP28 25G SR4', 25, 'SFP28', 'price_floor',
   '2026-01-15', 'https://fs.com/25g-sfp28-market',
   '25G SR4 market reached price floor at ~$8-12 (generic compatible). No further significant price decline expected. Stable supply from multiple Chinese manufacturers.',
   'low'),
  ('QSFP28 100G DR4', 100, 'QSFP28', 'price_drop',
   '2026-03-15', 'https://www.fiercetelecom.com/networking/100g-dr4-price-war',
   'FS.com price drop to $49 triggered industry-wide 100G DR4 repricing. New price floor establishing at $45-55 range.',
   'high')
ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 6. Update known issues count on transceivers (computed field)
-- ─────────────────────────────────────────────────────────────────────────────
UPDATE transceivers t SET known_issues_count = (
  SELECT COUNT(*) FROM product_issues pi WHERE pi.transceiver_id = t.id
);

UPDATE transceivers t SET documents_count = (
  SELECT COUNT(*) FROM product_documents pd WHERE pd.transceiver_id = t.id
);
