-- =============================================================================
-- Migration: Move Printer IP Addresses from machines to communications Table
-- Date: 2025-11-14
-- Purpose: Migrate printer IP data to communications table before removing
--          ipaddress1/2/3 columns from machines table
-- =============================================================================

-- STEP 1: Migrate printer IP addresses to communications table
-- Note: Printers use comstypeid = 1 (Network) for IP addresses
-- Use isprimary = 1 to indicate this is the primary network interface

INSERT INTO communications (machineid, comstypeid, address, isprimary, isactive, lastupdated)
SELECT
    m.machineid,
    1 AS comstypeid,  -- Network communication type
    m.ipaddress1 AS address,
    1 AS isprimary,   -- Primary network interface
    1 AS isactive,
    NOW() AS lastupdated
FROM machines m
WHERE m.machinetypeid = 15  -- Printers
  AND m.ipaddress1 IS NOT NULL
  AND m.ipaddress1 != ''
  AND NOT EXISTS (
      -- Don't insert if this printer already has a communications record
      SELECT 1 FROM communications c
      WHERE c.machineid = m.machineid
        AND c.comstypeid = 1
  );

-- =============================================================================
-- Verification Queries
-- =============================================================================

-- Check how many printer IPs were migrated
-- SELECT COUNT(*) as migrated_printer_ips
-- FROM communications c
-- INNER JOIN machines m ON c.machineid = m.machineid
-- WHERE m.machinetypeid = 15 AND c.comstypeid = 1;

-- Compare machines.ipaddress1 vs communications.address for printers
-- SELECT
--     m.machineid,
--     m.alias,
--     m.ipaddress1 as old_ip,
--     c.address as new_ip
-- FROM machines m
-- LEFT JOIN communications c ON m.machineid = c.machineid AND c.comstypeid = 1
-- WHERE m.machinetypeid = 15
-- ORDER BY m.machineid;

-- =============================================================================
-- Status: Ready to execute
-- Impact: Migrates 32 printer IP addresses to communications table
-- =============================================================================
