-- Migration 025: Fix details_verified quality gate + repair garbled ATGBICS records
-- Problem: details_verified = true when:
--   1. reach_label = '' (empty string passes IS NOT NULL)
--   2. part_number contains 'compatible-transceiver' (URL slug stored as PN)
-- ─────────────────────────────────────────────────────────────────────────────

-- Step 1: Fix part_numbers that are ATGBICS URL slugs
-- Extract the real OEM part number: take everything before "-r-compatible" or "-compatible"
UPDATE transceivers
SET
  part_number = UPPER(
    REGEXP_REPLACE(
      REGEXP_REPLACE(
        part_number,
        '-(nokia|cisco|juniper|arista|huawei|hp|hpe|dell|extreme|brocade|mellanox|intel|broadcom|netgear|foundry|calix|ciena|adtran|palo|fortinet|alcatel|ericsson|nec|fujitsu|infinera|ribbon|hitachi|rad|zhone|ubiquiti|mikrotik|avaya|enterasys|allied|planet|zyxel|dlink)$',
        '',
        'i'
      ),
      '-(r-compatible|compatible)(-transceiver.*)?$',
      '',
      'i'
    )
  ),
  updated_at = NOW()
WHERE
  part_number ILIKE '%-r-compatible%'
  OR part_number ILIKE '%-compatible-transceiver%';

-- Step 2: Extract reach_meters from reach_label where reach_meters = 0 but reach_label has data
UPDATE transceivers
SET
  reach_meters = CASE
    WHEN reach_label ILIKE '%km' THEN
      CAST(REGEXP_REPLACE(reach_label, '[^0-9]', '', 'g') AS INTEGER) * 1000
    WHEN reach_label ILIKE '%m' AND reach_label NOT ILIKE '%km' THEN
      CAST(REGEXP_REPLACE(reach_label, '[^0-9]', '', 'g') AS INTEGER)
    ELSE reach_meters
  END,
  updated_at = NOW()
WHERE reach_meters = 0
  AND reach_label IS NOT NULL
  AND reach_label != ''
  AND reach_label ~ '^\d+\s*(m|km)$';

-- Step 3: Also extract reach_label from slug where still missing
-- For records where slug contains NNkm pattern (e.g. scraped-3he16564aa-...-120km-...)
UPDATE transceivers
SET
  reach_label = (REGEXP_MATCH(slug, '(\d+km)'))[1],
  reach_meters = CAST((REGEXP_MATCH(slug, '(\d+)km'))[1] AS INTEGER) * 1000,
  updated_at = NOW()
WHERE
  (reach_label IS NULL OR reach_label = '')
  AND reach_meters = 0
  AND slug ~ '\d+km';

-- Step 4: Recompute all verification badges with the fixed criteria
-- (Updates details_verified, fully_verified for all affected transceivers)
SELECT recompute_all_verification();
