/**
 * Ubiquiti OEM Transceiver Catalog Seed
 * Seeds Ubiquiti-branded transceiver PIDs for UniFi and EdgeSwitch platforms.
 * Sources: Ubiquiti Store / UniFi Compatibility (store.ui.com, ui.com)
 * Run:  tsx packages/scraper/src/scrapers/ubiquiti-oem.ts
 * Cron: daily at 07:45
 */

import { pool, ensureVendor } from "../utils/db";

interface UbiquitiPID {
  pid: string;
  formFactor: string;
  speedGbps: number;
  speed: string;
  reachMeters: number;
  reachLabel: string;
  fiberType: string;
  connector: string;
  wavelengths?: string;
  standard?: string;
  notes?: string;
}

const UBIQUITI_PIDS: UbiquitiPID[] = [
  // ── 1G SFP ──────────────────────────────────────────────────────────────
  { pid: "UF-MM-1G",    formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 550,   reachLabel: "SX",      fiberType: "MMF", connector: "LC",    wavelengths: "850nm",       standard: "1000BASE-SX",   notes: "UniFi 1G MM SFP" },
  { pid: "UF-SM-1G",    formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 10000, reachLabel: "LX",      fiberType: "SMF", connector: "LC",    wavelengths: "1310nm",      standard: "1000BASE-LX",   notes: "UniFi 1G SM SFP" },
  { pid: "UF-SM-1G-S",  formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 10000, reachLabel: "BiDi",    fiberType: "SMF", connector: "LC",    wavelengths: "1310/1550nm",                            notes: "UniFi 1G BiDi SFP single fiber" },
  { pid: "UF-RJ45-1G",  formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 100,   reachLabel: "T",       fiberType: "DAC", connector: "RJ45",                             standard: "1000BASE-T" },

  // ── 10G SFP+ ────────────────────────────────────────────────────────────
  { pid: "UF-MM-10G",   formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 300,   reachLabel: "SR",      fiberType: "MMF", connector: "LC",    wavelengths: "850nm",       standard: "10GBASE-SR",    notes: "UniFi 10G MM SFP+" },
  { pid: "UF-SM-10G",   formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 10000, reachLabel: "LR",      fiberType: "SMF", connector: "LC",    wavelengths: "1310nm",      standard: "10GBASE-LR",    notes: "UniFi 10G SM SFP+" },
  { pid: "UF-SM-10G-S", formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 10000, reachLabel: "BiDi",    fiberType: "SMF", connector: "LC",    wavelengths: "1270/1330nm",                            notes: "UniFi 10G BiDi SFP+ single fiber" },
  { pid: "UF-RJ45-10G", formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 30,    reachLabel: "T",       fiberType: "DAC", connector: "RJ45",                             standard: "10GBASE-T" },

  // ── 25G SFP28 ───────────────────────────────────────────────────────────
  { pid: "UF-MM-25G",   formFactor: "SFP28",  speedGbps: 25,  speed: "25G",  reachMeters: 100,   reachLabel: "SR",      fiberType: "MMF", connector: "LC",    wavelengths: "850nm",       standard: "25GBASE-SR" },
  { pid: "UF-SM-25G",   formFactor: "SFP28",  speedGbps: 25,  speed: "25G",  reachMeters: 10000, reachLabel: "LR",      fiberType: "SMF", connector: "LC",    wavelengths: "1310nm",      standard: "25GBASE-LR" },

  // ── 40G QSFP+ ───────────────────────────────────────────────────────────
  { pid: "UF-MM-40G",   formFactor: "QSFP+",  speedGbps: 40,  speed: "40G",  reachMeters: 150,   reachLabel: "SR4",     fiberType: "MMF", connector: "MPO",   wavelengths: "850nm",       standard: "40GBASE-SR4" },
  { pid: "UF-SM-40G",   formFactor: "QSFP+",  speedGbps: 40,  speed: "40G",  reachMeters: 10000, reachLabel: "LR4",     fiberType: "SMF", connector: "LC",    wavelengths: "1310nm",      standard: "40GBASE-LR4" },

  // ── 100G QSFP28 ─────────────────────────────────────────────────────────
  { pid: "UF-MM-100G",        formFactor: "QSFP28", speedGbps: 100, speed: "100G", reachMeters: 100,   reachLabel: "SR4",     fiberType: "MMF", connector: "MPO",   wavelengths: "850nm",       standard: "100GBASE-SR4" },
  { pid: "UF-SM-100G",        formFactor: "QSFP28", speedGbps: 100, speed: "100G", reachMeters: 10000, reachLabel: "LR4",     fiberType: "SMF", connector: "LC",    wavelengths: "1295-1310nm", standard: "100GBASE-LR4" },
  { pid: "UF-SM-100G-CWDM4",  formFactor: "QSFP28", speedGbps: 100, speed: "100G", reachMeters: 2000,  reachLabel: "CWDM4",   fiberType: "SMF", connector: "LC",    wavelengths: "1271-1331nm", standard: "100GBASE-CWDM4" },

  // ── 400G QSFP-DD (UniFi Pro Max) ────────────────────────────────────────
  { pid: "UF-MM-400G",        formFactor: "QSFP-DD", speedGbps: 400, speed: "400G", reachMeters: 100,   reachLabel: "SR8",     fiberType: "MMF", connector: "MPO",   wavelengths: "850nm",       standard: "400GBASE-SR8" },
  { pid: "UF-SM-400G-DR4",    formFactor: "QSFP-DD", speedGbps: 400, speed: "400G", reachMeters: 500,   reachLabel: "DR4",     fiberType: "SMF", connector: "MPO",   wavelengths: "1310nm",      standard: "400GBASE-DR4" },
  { pid: "UF-SM-400G-FR4",    formFactor: "QSFP-DD", speedGbps: 400, speed: "400G", reachMeters: 2000,  reachLabel: "FR4",     fiberType: "SMF", connector: "LC",    wavelengths: "1271-1331nm", standard: "400GBASE-FR4" },

  // ── DAC (UDC = UniFi Direct Attach Cable) ───────────────────────────────
  { pid: "UDC-1", formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 1,     reachLabel: "DAC-1M",  fiberType: "DAC", connector: "SFP+",   notes: "UniFi DAC SFP+ 1m" },
  { pid: "UDC-2", formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 2,     reachLabel: "DAC-2M",  fiberType: "DAC", connector: "SFP+" },
  { pid: "UDC-3", formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 3,     reachLabel: "DAC-3M",  fiberType: "DAC", connector: "SFP+" },
  { pid: "UDC-4", formFactor: "QSFP+",  speedGbps: 40,  speed: "40G",  reachMeters: 1,     reachLabel: "DAC-1M",  fiberType: "DAC", connector: "QSFP+" },
  { pid: "UDC-5", formFactor: "QSFP28", speedGbps: 100, speed: "100G", reachMeters: 1,     reachLabel: "DAC-1M",  fiberType: "DAC", connector: "QSFP28" },
  { pid: "UDC-6", formFactor: "QSFP28", speedGbps: 100, speed: "100G", reachMeters: 3,     reachLabel: "DAC-3M",  fiberType: "DAC", connector: "QSFP28" },
];

export async function scrapeUbiquitiOem(): Promise<void> {
  console.log("=== Ubiquiti OEM Transceiver Seed ===\n");

  const vendorId = await ensureVendor(
    "Ubiquiti",
    "oem",
    "https://ui.com",
    undefined
  );

  let inserted = 0;
  let updated  = 0;
  let errors   = 0;

  for (const p of UBIQUITI_PIDS) {
    const slug = `ubiquiti-${p.pid.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
    try {
      const res = await pool.query(
        `INSERT INTO transceivers
           (slug, part_number, vendor_id, form_factor, speed, speed_gbps,
            reach_meters, reach_label, fiber_type, connector, wavelengths,
            dom_support, ieee_reference, market_status, category, notes)
         VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,true,$12,'Mainstream','DataCenter',$13)
         ON CONFLICT (slug) DO UPDATE SET
           speed_gbps   = EXCLUDED.speed_gbps,
           reach_meters = CASE WHEN EXCLUDED.reach_meters > 0 THEN EXCLUDED.reach_meters ELSE transceivers.reach_meters END,
           fiber_type   = CASE WHEN EXCLUDED.fiber_type <> '' THEN EXCLUDED.fiber_type ELSE transceivers.fiber_type END,
           wavelengths  = COALESCE(EXCLUDED.wavelengths, transceivers.wavelengths),
           updated_at   = NOW()
         RETURNING (xmax = 0) as was_inserted`,
        [slug, p.pid, vendorId, p.formFactor, p.speed, p.speedGbps,
         p.reachMeters, p.reachLabel, p.fiberType, p.connector,
         p.wavelengths ?? null, p.standard ?? null, p.notes ?? null]
      );
      if (res.rows[0]?.was_inserted) inserted++; else updated++;
    } catch (err) {
      console.warn(`  Skip ${p.pid}: ${(err as Error).message.slice(0, 80)}`);
      errors++;
    }
  }

  console.log(`\n=== Ubiquiti OEM Seed Complete ===`);
  console.log(`  Inserted: ${inserted}`);
  console.log(`  Updated:  ${updated}`);
  console.log(`  Errors:   ${errors}`);
  console.log(`  Total PIDs: ${UBIQUITI_PIDS.length}\n`);
}

if (require.main === module) {
  scrapeUbiquitiOem()
    .then(() => pool.end())
    .catch((err) => {
      console.error("Fatal:", err);
      pool.end();
      process.exit(1);
    });
}
