-- Migration 021: Procurement Intelligence Demo Data (corrected schema)
-- Seeds realistic procurement signals, ABC classes, stock observations

-- ─────────────────────────────────────────────────────────────────────────────
-- 1. ABC Classification demo entries
-- abc_classification: transceiver_id, abc_class, obs_90d, compat_count,
--   vendor_count, price_volatility, demand_score, supply_risk, computed_at
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO abc_classification (
  transceiver_id, abc_class, obs_90d, compat_count, vendor_count,
  price_volatility, demand_score, supply_risk, computed_at
)
SELECT
  t.id,
  CASE
    WHEN t.speed_gbps >= 400 THEN 'A'
    WHEN t.speed_gbps >= 100 THEN 'A'
    WHEN t.speed_gbps >= 25  THEN 'B'
    WHEN t.speed_gbps >= 10  THEN 'B'
    ELSE 'C'
  END,
  FLOOR(10 + random() * 90)::INTEGER,
  FLOOR(5  + random() * 50)::INTEGER,
  FLOOR(1  + random() * 8)::INTEGER,
  ROUND((random() * 0.25)::NUMERIC, 4),
  ROUND(CASE
    WHEN t.speed_gbps >= 400 THEN 75 + random() * 24
    WHEN t.speed_gbps >= 100 THEN 55 + random() * 30
    WHEN t.speed_gbps >= 25  THEN 30 + random() * 25
    ELSE 5 + random() * 25
  END::NUMERIC, 2),
  CASE WHEN random() > 0.7 THEN 'high' WHEN random() > 0.4 THEN 'medium' ELSE 'low' END,
  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
-- reorder_signals: transceiver_id, signal, signal_strength, reasons,
--   stock_trend, price_trend, lead_time_weeks, hype_phase, computed_at, expires_at
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO reorder_signals (
  transceiver_id, signal, signal_strength, reasons,
  stock_trend, price_trend, lead_time_weeks, hype_phase,
  computed_at, expires_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 ILIKE '%DR%'          THEN 'buy_now'
    WHEN t.speed_gbps = 100  AND t.reach_label ILIKE '%ZR%'          THEN 'wait'
    WHEN t.speed_gbps = 400  AND t.reach_label ILIKE '%ZR%'          THEN 'wait'
    WHEN t.speed_gbps = 25                                            THEN 'monitor'
    WHEN t.speed_gbps = 10   AND t.reach_label ILIKE '%LR%'          THEN 'hold'
    ELSE 'monitor'
  END,
  ROUND(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::NUMERIC, 2),
  CASE
    WHEN t.speed_gbps >= 400 AND t.form_factor = 'QSFP-DD'
      THEN '["Price near 12-month low","Adoption entering slope of enlightenment","Hyperscaler demand confirmed (AWS $105B CapEx 2026)","Lead times stable 8-12 weeks"]'::jsonb
    WHEN t.speed_gbps = 100 AND t.reach_label ILIKE '%DR%'
      THEN '["DR4 pricing dropped 18% Q1 2026","High switch compat (400+ switches)","FS.com and 10Gtek stock available","Strong Flexoptix catalog coverage"]'::jsonb
    WHEN t.speed_gbps = 100 AND t.reach_label ILIKE '%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 ILIKE '%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 and stable","No lifecycle event triggered","Normal replenishment timing applies"]'::jsonb
    ELSE '["Stable pricing","No urgent lifecycle event","Standard replenishment cycle"]'::jsonb
  END,
  CASE WHEN random() > 0.5 THEN 'declining' WHEN random() > 0.3 THEN 'stable' ELSE 'increasing' END,
  CASE WHEN t.speed_gbps >= 100 THEN 'falling' WHEN random() > 0.4 THEN 'stable' ELSE 'falling' END,
  CASE
    WHEN t.speed_gbps >= 400 THEN FLOOR(2 + random() * 3)::INTEGER
    WHEN t.speed_gbps >= 100 THEN FLOOR(1 + random() * 2)::INTEGER
    ELSE 1
  END,
  CASE
    WHEN t.speed_gbps >= 400 THEN 'SLOPE_OF_ENLIGHTENMENT'
    WHEN t.speed_gbps >= 100 THEN 'PLATEAU_OF_PRODUCTIVITY'
    WHEN t.speed_gbps >= 25  THEN 'PLATEAU_OF_PRODUCTIVITY'
    WHEN t.speed_gbps >= 10  THEN 'LEGACY_DECLINE'
    ELSE 'LEGACY_DECLINE'
  END,
  NOW() - (random() * INTERVAL '1 hour'),
  NOW() + INTERVAL '24 hours'
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 demo
-- stock_snapshots: transceiver_id, vendor_id, stock_level, stock_quantity,
--   incoming_quantity, incoming_eta, lead_time_days, moq, price_breaks,
--   source_url, crawler_confidence, scraped_at
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO stock_snapshots (
  transceiver_id, vendor_id,
  stock_level, stock_quantity, incoming_quantity, incoming_eta,
  lead_time_days, moq, source_url, crawler_confidence, scraped_at
)
SELECT
  t.id,
  v.id,
  CASE
    WHEN random() > 0.6 THEN 'in_stock'
    WHEN random() > 0.3 THEN 'limited'
    ELSE 'unknown'
  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 CURRENT_DATE + FLOOR(14 + random() * 28)::INTEGER ELSE NULL END,
  FLOOR(3 + random() * 14)::INTEGER,
  CASE WHEN t.speed_gbps >= 100 THEN 5 ELSE 1 END,
  v.website_url,
  ROUND((0.70 + random() * 0.28)::NUMERIC, 2),
  NOW() - (random() * INTERVAL '6 hours')
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.scraped_at > NOW() - INTERVAL '12 hours'
)
LIMIT 300
ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 4. Market intelligence — expand current data
-- market_intelligence: intel_type, title, summary, relevance_score,
--   technologies, buy_signal_implication, impact_horizon_months,
--   source_url, source_name, published_at
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO market_intelligence (
  intel_type, title, summary, relevance_score,
  technologies, buy_signal_implication, impact_horizon_months,
  source_url, source_name, published_at
) VALUES
  ('supply_chain',
   '400G ZR+ Volume Shipments Accelerating H1 2026',
   'Multiple sources confirm 400G ZR+ module shipments ramping >40% QoQ. Coherent, Lumentum, II-VI all report order surge. Pricing dropped from €350 to €285 average since Jan 2026. Further 15-20% decline expected by Q3.',
   0.88, ARRAY['400G','ZR+','QSFP-DD'], 'buy_now', 3,
   'https://www.lightreading.com/400g-zr-market-2026', 'LightReading',
   '2026-03-28 09:00:00+00'),

  ('supply_chain',
   '100G DR4 Price War: FS.com Triggers Industry Reset to $49',
   'FS.com reduced 100G QSFP28 DR4 pricing to $49 (from $67) March 2026. 10Gtek and ATGBICS responded within 72h. Flexoptix adjusted to €52. Structural price reset — new floor establishing at $45-55.',
   0.95, ARRAY['100G','DR4','QSFP28'], 'buy_now', 2,
   'https://www.fiercetelecom.com/networking/100g-dr4-price-war', 'FierceTelecom',
   '2026-03-15 14:00:00+00'),

  ('distributor_lead_time',
   'QSFP28 100G SR4 Lead Times Extended to 12-16 Weeks — InnoLight Allocation',
   'Farnell reports QSFP28-100G-SR4 lead times extended 12-16 weeks due to component shortages at InnoLight and Lumentum. Spot market prices €15-20 above list. Pre-order Q2/Q3 requirements now.',
   0.91, ARRAY['100G','SR4','QSFP28'], 'buy_now', 3,
   'https://farnell.com/lead-times-q2-2026', 'Farnell',
   '2026-03-22 10:00:00+00'),

  ('standard_draft',
   'IEEE 802.3df 200G/400G/800G PAM4 — Ballot Q2 2026',
   'IEEE 802.3 Task Force 802.3df targeting 200G-per-lane PAM4 standard ballot Q2 2026. Enables 800G single-mode modules at sub-€300 by 2027. Will accelerate 400G DR4/FR4 price decline.',
   0.82, ARRAY['800G','400G','PAM4','OSFP'], 'monitor', 9,
   'https://www.ieee802.org/3/df/index.html', 'IEEE 802.3',
   '2026-03-10 08:00:00+00'),

  ('distributor_lead_time',
   'SFP28 25G Short-Run Availability Improving — Lead Times 2-4 Weeks',
   'Mouser reports SFP28 25G SR/LR availability improving significantly Q1 2026. Lead times for generic-compatible SFP28 dropped from 8-10 weeks to 2-4 weeks. Pricing flat to -5% YoY.',
   0.79, ARRAY['25G','SFP28','SR','LR'], 'monitor', 1,
   'https://mouser.com/optics-availability-q1-2026', 'Mouser Electronics',
   '2026-03-18 11:00:00+00'),

  ('trade_show',
   'Arista 800G OSFP Platform Confirmed — Q3 2026 Delivery',
   'Arista Networks confirmed 7800R3-48CQFM-LC supporting 800G OSFP modules, Q3 2026. First enterprise switching platform with native 800G. 400G prices will accelerate decline in H2 2026 as 800G creates pull-through demand.',
   0.90, ARRAY['800G','OSFP','400G','Arista'], 'buy_now', 6,
   'https://eos.arista.com/800g-announcement', 'Arista Community',
   '2026-03-05 09:00:00+00'),

  ('tender',
   'EU TED: Deutsche Bahn €3.8M Optical Transceiver Tender Q4 2026',
   'Deutsche Bahn AG tender for 40,000+ QSFP28 100G LR4 and SFP28 25G SR4 for ETCS signalling upgrades. Contract value €3.8M over 3 years. Delivery from Q4 2026. Strong European demand signal.',
   0.76, ARRAY['100G','LR4','25G','SR4'], 'buy_now', 6,
   'https://ted.europa.eu/search?q=optical+transceiver', 'EU TED',
   '2026-03-30 16:00:00+00'),

  ('capex_cycle',
   'Transceiver Market Q1 2026: $1.4B Revenue, Up 28% YoY — AI Clusters Drive Growth',
   'LightCounting Q1 2026: transceiver market $1.4B, up 28% YoY driven by hyperscaler AI buildouts. 400G QSFP-DD now 38% of revenue. 100G declining share but stable volume. 800G <1% today. Flexoptix-addressable segment ~12% of total.',
   0.93, ARRAY['400G','QSFP-DD','100G','800G'], 'buy_now', 3,
   'https://lightcounting.com/q1-2026-market-report', 'LightCounting Market Research',
   '2026-04-01 08:00:00+00')

ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 5. Product lifecycle events — additional entries
-- product_lifecycle_events: event_type, title, description, technology,
--   effective_date, source_url, source_name, impact_level, buy_signal
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO product_lifecycle_events (
  event_type, title, description, technology,
  effective_date, source_url, source_name, impact_level, buy_signal
) VALUES
  ('standard_ratified', 'QSFP28 100G LR4 — IEEE 802.3bs Mature Standard',
   'IEEE 802.3bs 400GbE fully ratified. 100G LR4 is now the established enterprise standard for 10km+ datacenter interconnect. Full multi-vendor ecosystem, price floor establishing.',
   '100G LR4', '2025-12-01',
   'https://ieee802.org/3/bs/', 'IEEE 802.3', 'medium', 'buy_now'),

  ('eol_announced', 'Cisco SFP-10G-SR EOL Announced — Sep 2026',
   'Cisco SFP-10G-SR EOL 2026-09-30. Last day of support 2031-09-30. Volume declining rapidly. Generic compatible alternatives at 60% lower cost readily available.',
   '10G SR', '2026-09-30',
   'https://www.cisco.com/c/en/us/products/eol.html', 'Cisco', 'medium', 'hold'),

  ('standard_ratified', '400ZR OIF Standard Ratified — Coherent Pluggable Era',
   'OIF 400ZR standard fully ratified and deployed at scale. Now supported by Cisco, Arista, Juniper, Nokia. Pricing dropped 45% from initial release. Market entering slope of enlightenment.',
   '400G ZR', '2022-06-15',
   'https://400zr.net/', 'OIF', 'high', 'buy_now'),

  ('standard_draft', '800G OSFP MSA Draft v2.0 Published',
   '800G OSFP MSA draft v2.0 published. Sampling from Coherent and Lumentum expected Q2 2026. General availability Q3-Q4 2026. Will displace 400G QSFP-DD in hyperscale builds from 2027.',
   '800G OSFP', '2026-03-01',
   'https://opensystemsintegration.com/800G-MSA', 'OSFP MSA', 'high', 'monitor'),

  ('price_floor', 'SFP28 25G SR4 — Price Floor Reached at €8-12',
   '25G SR4 market reached structural price floor ~€8-12 (generic compatible). Multiple Chinese manufacturers (InnoLight, Eoptolink) in volume production. No further significant decline expected.',
   '25G SFP28', '2026-01-15',
   'https://fs.com/25g-sfp28-market', 'FS.com', 'low', 'buy_now'),

  ('supply_chain', '100G DR4 Price Reset — New Floor Establishing at $45-55',
   'FS.com price drop to $49 triggered industry-wide 100G DR4 repricing March 2026. New competitive floor at $45-55 range. Flexoptix EUR equivalent €44-52. Optimal buy window now open.',
   '100G DR4', '2026-03-15',
   'https://www.fiercetelecom.com/networking/100g-dr4-price-war', 'FierceTelecom', 'high', 'buy_now')

ON CONFLICT DO NOTHING;

-- ─────────────────────────────────────────────────────────────────────────────
-- 6. Update computed count fields
-- ─────────────────────────────────────────────────────────────────────────────
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
);

-- Summary
SELECT
  (SELECT COUNT(*) FROM abc_classification)       AS abc_entries,
  (SELECT COUNT(*) FROM reorder_signals)           AS reorder_signals,
  (SELECT COUNT(*) FROM stock_snapshots)           AS stock_snapshots,
  (SELECT COUNT(*) FROM market_intelligence)       AS market_intel,
  (SELECT COUNT(*) FROM product_lifecycle_events)  AS lifecycle_events;
