-- Update vw_network_devices view for Phase 3 (legacy tables dropped)
-- Date: 2025-11-25
-- Purpose: Network devices now come from machines table (16-20) and printers table
-- Legacy tables (idfs, servers, switches, cameras, accesspoints) have been dropped

USE shopdb;

DROP VIEW IF EXISTS vw_network_devices;

CREATE VIEW vw_network_devices AS
-- Printers from separate table
SELECT
    'Printer' AS device_type,
    p.printerid AS device_id,
    p.printerwindowsname AS device_name,
    p.modelid,
    m.modelnumber,
    v.vendor,
    p.serialnumber,
    p.ipaddress,
    NULL AS description,
    p.maptop,
    p.mapleft,
    p.isactive,
    NULL AS idfid,
    NULL AS idfname,
    NULL AS macaddress,
    p.fqdn
FROM printers p
LEFT JOIN models m ON p.modelid = m.modelnumberid
LEFT JOIN vendors v ON m.vendorid = v.vendorid

UNION ALL

-- Network devices from machines table (machinetypeid 16-20)
-- 16=Access Point, 17=IDF, 18=Camera, 19=Switch, 20=Server
SELECT
    mt.machinetype AS device_type,
    ma.machineid AS device_id,
    COALESCE(ma.alias, ma.machinenumber) AS device_name,
    ma.modelnumberid AS modelid,
    mo.modelnumber,
    ve.vendor,
    ma.serialnumber,
    c.address AS ipaddress,
    ma.machinenotes AS description,
    ma.maptop,
    ma.mapleft,
    ma.isactive,
    NULL AS idfid,
    NULL AS idfname,
    c.macaddress,
    NULL AS fqdn
FROM machines ma
INNER JOIN machinetypes mt ON ma.machinetypeid = mt.machinetypeid
LEFT JOIN models mo ON ma.modelnumberid = mo.modelnumberid
LEFT JOIN vendors ve ON mo.vendorid = ve.vendorid
LEFT JOIN communications c ON ma.machineid = c.machineid AND c.isprimary = 1 AND c.comstypeid = 1
WHERE mt.machinetypeid IN (16, 17, 18, 19, 20);

-- Show updated view
SELECT 'View updated successfully' AS status;

SELECT device_type, COUNT(*) AS total
FROM vw_network_devices
WHERE isactive = 1
GROUP BY device_type
ORDER BY device_type;
