-- =============================================================================
-- PHASE 1.5: Migrate Equipment IP Addresses to Communications Table
-- =============================================================================
-- Date: 2025-11-21
-- Purpose: Migrate equipment (CNC, mills, lathes, etc.) IP addresses from
--          machines.ipaddress1/ipaddress2 to communications table
--
-- CRITICAL: Run this AFTER Phase 1 (infrastructure created) and
--           BEFORE removing ipaddress columns from machines table
--
-- Estimated Time: 1-2 minutes
-- Records: ~275 equipment IP addresses
-- =============================================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

SELECT '============================================================' AS '';
SELECT 'PHASE 1.5: MIGRATE EQUIPMENT IP ADDRESSES' AS '';
SELECT '============================================================' AS '';
SELECT CONCAT('Start time: ', NOW()) AS '';
SELECT '' AS '';

-- =============================================================================
-- STEP 1: Pre-migration checks
-- =============================================================================

SELECT 'Pre-migration checks:' AS '';
SELECT '' AS '';

-- Check communications table exists
SET @comms_exists = (
    SELECT COUNT(*) FROM information_schema.tables
    WHERE table_schema = 'shopdb' AND table_name = 'communications'
);

SELECT CASE
    WHEN @comms_exists = 1 THEN '✓ Communications table exists'
    ELSE '⚠️ ERROR: Communications table not found - run Phase 1 first!'
END AS status;

-- Check comstypes populated
SET @comstypes_count = (SELECT COUNT(*) FROM comstypes WHERE typename = 'Network' OR typename = 'Network_Interface');

SELECT CASE
    WHEN @comstypes_count >= 1 THEN CONCAT('✓ Network comstypes exist (', @comstypes_count, ')')
    ELSE '⚠️ ERROR: Network comstypes not found - run Phase 1 first!'
END AS status;

-- Check machines table has ipaddress columns
SET @has_ip_columns = (
    SELECT COUNT(*) FROM information_schema.columns
    WHERE table_schema = 'shopdb'
    AND table_name = 'machines'
    AND column_name IN ('ipaddress1', 'ipaddress2')
);

SELECT CASE
    WHEN @has_ip_columns = 2 THEN '✓ Machines table has ipaddress1/ipaddress2 columns'
    WHEN @has_ip_columns = 0 THEN '⚠️ WARNING: IP columns already removed - migration may have already run'
    ELSE '⚠️ WARNING: Only some IP columns exist'
END AS status;

SELECT '' AS '';

-- Count equipment with IP addresses
SELECT 'Equipment IP address statistics:' AS '';
SELECT
    'Equipment with ipaddress1' AS category,
    COUNT(*) AS count
FROM machines
WHERE (pctypeid IS NULL OR pctypeid = 0)  -- Equipment only (not PCs)
  AND ipaddress1 IS NOT NULL
  AND ipaddress1 != ''
  AND ipaddress1 NOT IN ('X', 'TBD', 'N/A', 'x')
UNION ALL
SELECT
    'Equipment with ipaddress2',
    COUNT(*)
FROM machines
WHERE (pctypeid IS NULL OR pctypeid = 0)
  AND ipaddress2 IS NOT NULL
  AND ipaddress2 != ''
  AND ipaddress2 NOT IN ('X', 'TBD', 'N/A', 'x')
UNION ALL
SELECT
    'Existing equipment communications',
    COUNT(DISTINCT c.machineid)
FROM communications c
JOIN machines m ON c.machineid = m.machineid
WHERE (m.pctypeid IS NULL OR m.pctypeid = 0);

SELECT '' AS '';

-- =============================================================================
-- STEP 2: Create backup of machine IP data
-- =============================================================================

SELECT 'Creating backup table...' AS '';

DROP TABLE IF EXISTS _backup_equipment_ips_phase1_5;
CREATE TABLE _backup_equipment_ips_phase1_5 AS
SELECT
    machineid,
    machinenumber,
    alias,
    machinetypeid,
    ipaddress1,
    ipaddress2,
    NOW() AS backup_timestamp
FROM machines
WHERE (pctypeid IS NULL OR pctypeid = 0)  -- Equipment only
  AND (
    (ipaddress1 IS NOT NULL AND ipaddress1 != '' AND ipaddress1 NOT IN ('X', 'TBD', 'N/A', 'x'))
    OR
    (ipaddress2 IS NOT NULL AND ipaddress2 != '' AND ipaddress2 NOT IN ('X', 'TBD', 'N/A', 'x'))
  );

SELECT CONCAT('✓ Backup created: _backup_equipment_ips_phase1_5 (', COUNT(*), ' equipment records)') AS status
FROM _backup_equipment_ips_phase1_5;

SELECT '' AS '';

-- =============================================================================
-- STEP 3: Migrate ipaddress1 (primary interface)
-- =============================================================================

SELECT 'Migrating ipaddress1 (primary interface)...' AS '';

-- Get comstypeid for Network type
SET @network_comstypeid = (
    SELECT comstypeid FROM comstypes
    WHERE typename IN ('Network', 'Network_Interface')
    LIMIT 1
);

INSERT INTO communications (
    machineid,
    comstypeid,
    address,
    isprimary,
    interfacename,
    isactive,
    lastupdated
)
SELECT
    m.machineid,
    @network_comstypeid AS comstypeid,
    m.ipaddress1 AS address,
    1 AS isprimary,                        -- Primary interface
    'Equipment Interface 1' AS interfacename,
    1 AS isactive,
    NOW() AS lastupdated
FROM machines m
WHERE (m.pctypeid IS NULL OR m.pctypeid = 0)  -- Equipment only (not PCs)
  AND m.ipaddress1 IS NOT NULL
  AND m.ipaddress1 != ''
  AND m.ipaddress1 NOT IN ('X', 'TBD', 'N/A', 'x')  -- Exclude placeholder values
  AND NOT EXISTS (
      -- Don't insert if equipment already has a primary communication record
      SELECT 1 FROM communications c
      WHERE c.machineid = m.machineid
        AND c.isprimary = 1
        AND c.address = m.ipaddress1
  );

SELECT CONCAT('✓ Migrated ', ROW_COUNT(), ' primary IP addresses (ipaddress1)') AS status;

SELECT '' AS '';

-- =============================================================================
-- STEP 4: Migrate ipaddress2 (secondary interface)
-- =============================================================================

SELECT 'Migrating ipaddress2 (secondary interface)...' AS '';

INSERT INTO communications (
    machineid,
    comstypeid,
    address,
    isprimary,
    interfacename,
    isactive,
    lastupdated
)
SELECT
    m.machineid,
    @network_comstypeid AS comstypeid,
    m.ipaddress2 AS address,
    0 AS isprimary,                        -- Secondary interface
    'Equipment Interface 2' AS interfacename,
    1 AS isactive,
    NOW() AS lastupdated
FROM machines m
WHERE (m.pctypeid IS NULL OR m.pctypeid = 0)  -- Equipment only (not PCs)
  AND m.ipaddress2 IS NOT NULL
  AND m.ipaddress2 != ''
  AND m.ipaddress2 NOT IN ('X', 'TBD', 'N/A', 'x')  -- Exclude placeholder values
  AND NOT EXISTS (
      -- Don't insert if equipment already has this communication record
      SELECT 1 FROM communications c
      WHERE c.machineid = m.machineid
        AND c.address = m.ipaddress2
  );

SELECT CONCAT('✓ Migrated ', ROW_COUNT(), ' secondary IP addresses (ipaddress2)') AS status;

SELECT '' AS '';

-- =============================================================================
-- STEP 5: Verification
-- =============================================================================

SELECT 'Verifying migration...' AS '';
SELECT '' AS '';

-- Show summary
SELECT 'Migration summary:' AS '';
SELECT
    'Equipment in backup table' AS category,
    COUNT(*) AS count
FROM _backup_equipment_ips_phase1_5
UNION ALL
SELECT
    'Equipment with ipaddress1 (before migration)',
    COUNT(*)
FROM _backup_equipment_ips_phase1_5
WHERE ipaddress1 IS NOT NULL AND ipaddress1 != '' AND ipaddress1 NOT IN ('X', 'TBD', 'N/A', 'x')
UNION ALL
SELECT
    'Equipment with ipaddress2 (before migration)',
    COUNT(*)
FROM _backup_equipment_ips_phase1_5
WHERE ipaddress2 IS NOT NULL AND ipaddress2 != '' AND ipaddress2 NOT IN ('X', 'TBD', 'N/A', 'x')
UNION ALL
SELECT
    'Equipment communications (after migration)',
    COUNT(DISTINCT c.machineid)
FROM communications c
JOIN machines m ON c.machineid = m.machineid
WHERE (m.pctypeid IS NULL OR m.pctypeid = 0);

SELECT '' AS '';

-- Show sample of migrated equipment
SELECT 'Sample of migrated equipment IPs:' AS '';
SELECT
    m.machineid,
    m.machinenumber,
    m.alias,
    COUNT(c.comid) AS interface_count,
    GROUP_CONCAT(
        CONCAT(c.address, ' (', IF(c.isprimary=1, 'Primary', 'Secondary'), ')')
        ORDER BY c.isprimary DESC
        SEPARATOR ', '
    ) AS ip_addresses
FROM machines m
JOIN communications c ON m.machineid = c.machineid
JOIN _backup_equipment_ips_phase1_5 b ON m.machineid = b.machineid
WHERE (m.pctypeid IS NULL OR m.pctypeid = 0)
GROUP BY m.machineid, m.machinenumber, m.alias
ORDER BY m.machinenumber
LIMIT 10;

SELECT '' AS '';

-- Check for missing migrations
SET @missing_migrations = (
    SELECT COUNT(*)
    FROM _backup_equipment_ips_phase1_5 b
    WHERE (b.ipaddress1 IS NOT NULL AND b.ipaddress1 != '' AND b.ipaddress1 NOT IN ('X', 'TBD', 'N/A', 'x'))
      AND NOT EXISTS (
          SELECT 1 FROM communications c
          WHERE c.machineid = b.machineid
      )
);

SELECT CASE
    WHEN @missing_migrations = 0 THEN '✓ All equipment IPs successfully migrated'
    ELSE CONCAT('⚠️ WARNING: ', @missing_migrations, ' equipment records not migrated - review logs')
END AS status;

SELECT '' AS '';

-- =============================================================================
-- STEP 6: Final summary
-- =============================================================================

SELECT '============================================================' AS '';
SELECT '✓✓✓ EQUIPMENT IP MIGRATION COMPLETE ✓✓✓' AS '';
SELECT '============================================================' AS '';
SELECT '' AS '';

SELECT 'Backup table created:' AS '';
SELECT '  _backup_equipment_ips_phase1_5' AS '';
SELECT '' AS '';

SELECT 'Next steps:' AS '';
SELECT '  1. Verify equipment IPs in communications table' AS '';
SELECT '  2. Test application pages using equipment IPs' AS '';
SELECT '  3. Once verified, run remove_legacy_ip_columns.sql to drop ipaddress1/2 columns' AS '';
SELECT '' AS '';

SELECT 'IMPORTANT: Keep backup table for 30 days for rollback if needed' AS '';

SELECT '' AS '';
SELECT CONCAT('Completed at: ', NOW()) AS '';
SELECT '============================================================' AS '';

SET SQL_SAFE_UPDATES = 1;

-- =============================================================================
-- ROLLBACK PROCEDURE (if needed)
-- =============================================================================
--
-- If migration needs to be rolled back:
--
-- 1. Delete migrated communications:
-- DELETE c FROM communications c
-- JOIN _backup_equipment_ips_phase1_5 b ON c.machineid = b.machineid
-- WHERE c.interfacename LIKE 'Equipment Interface%';
--
-- 2. Restore ipaddress columns (if dropped):
-- ALTER TABLE machines
--   ADD COLUMN ipaddress1 CHAR(50) DEFAULT NULL,
--   ADD COLUMN ipaddress2 CHAR(50) DEFAULT NULL;
--
-- 3. Restore IP addresses:
-- UPDATE machines m
-- JOIN _backup_equipment_ips_phase1_5 b ON m.machineid = b.machineid
-- SET m.ipaddress1 = b.ipaddress1,
--     m.ipaddress2 = b.ipaddress2;
--
-- =============================================================================
