-- =====================================================
-- SCRIPT 01: Migrate PC Records to Machines Table
-- =====================================================
-- Date: 2025-11-06
-- Purpose: Migrate all PC records from pc table to machines table
-- Status: REQUIRES TESTING - Creates backup table first
-- Estimated Time: 5-10 minutes
-- Records: ~277 PCs
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

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

SELECT '========================================' AS '';
SELECT 'PC TO MACHINES MIGRATION' AS '';
SELECT '========================================' AS '';
SELECT '' AS '';

-- Count PCs to migrate
SELECT CONCAT('PCs to migrate: ', COUNT(*)) AS info FROM pc WHERE isactive = 1;
SELECT CONCAT('Current machines: ', COUNT(*)) AS info FROM machines WHERE isactive = 1;

-- Show PC type distribution
SELECT 'PC Type Distribution:' AS '';
SELECT pt.typename, COUNT(*) as count
FROM pc p
JOIN pctype pt ON p.pctypeid = pt.pctypeid
WHERE p.isactive = 1
GROUP BY pt.typename
ORDER BY count DESC;

SELECT '' AS '';

-- =====================================================
-- STEP 2: Create mapping between pctype and machine types
-- =====================================================

-- Create temporary mapping table
CREATE TEMPORARY TABLE temp_pctype_mapping (
    pctypeid INT,
    typename VARCHAR(50),
    target_machinetypeid INT
);

-- Map PC types to new machine types
INSERT INTO temp_pctype_mapping (pctypeid, typename, target_machinetypeid)
SELECT
    pt.pctypeid,
    pt.typename,
    CASE pt.typename
        WHEN 'Standard' THEN 33          -- Standard PC (Phase 2)
        WHEN 'Shopfloor' THEN 35         -- Shopfloor PC (Phase 2)
        WHEN 'Engineer' THEN 34          -- Engineering PC (Phase 2)
        WHEN 'Server' THEN 33            -- Map to Standard PC
        WHEN 'VM' THEN 33                -- Map to Standard PC
        WHEN 'Laptop' THEN 33            -- Map to Standard PC
        WHEN 'CMM' THEN 33               -- CMM is mislabeled, map to Standard PC
        WHEN 'Uncategorized' THEN 33     -- Map to Standard PC
        WHEN 'Wax / Trace' THEN 33       -- Map to Standard PC
        ELSE 33                          -- Default to Standard PC
    END
FROM pctype pt;

SELECT 'PC Type Mapping Created:' AS '';
SELECT * FROM temp_pctype_mapping;
SELECT '' AS '';

-- =====================================================
-- STEP 3: Create backup of PC data
-- =====================================================

DROP TABLE IF EXISTS pc_backup_phase2;
CREATE TABLE pc_backup_phase2 AS SELECT * FROM pc;

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

SELECT '' AS '';

-- =====================================================
-- STEP 4: Create temporary table for new machine records
-- =====================================================

DROP TEMPORARY TABLE IF EXISTS temp_new_machines;
CREATE TEMPORARY TABLE temp_new_machines AS
SELECT
    NULL AS new_machineid,                -- Will be auto-generated
    p.pcid AS old_pcid,                   -- Track source PC

    -- Machine type based on PC type
    m.target_machinetypeid AS machinetypeid,

    -- PC identification fields
    COALESCE(p.hostname, CONCAT('PC_', p.pcid)) AS machinenumber,  -- Use hostname or generate PC_[id]
    p.hostname AS hostname,
    COALESCE(p.hostname, CONCAT('PC_', p.pcid)) AS alias,  -- Set alias same as machinenumber
    p.loggedinuser,

    -- Model and vendor
    p.modelnumberid,
    NULL AS controllertypeid,             -- PCs don't have controllers
    NULL AS controllerosid,               -- PCs don't have controller OS
    p.serialnumber,

    -- OS and status
    p.osid,
    CASE
        WHEN p.pcstatusid IS NOT NULL THEN p.pcstatusid
        ELSE 3  -- Default to 'In Use' (machinestatusid 3)
    END AS machinestatusid,
    p.pctypeid,

    -- Business unit (default to 1 if not set)
    COALESCE(
        (SELECT businessunitid FROM machines WHERE machinenumber = p.machinenumber AND isactive = 1 LIMIT 1),
        1
    ) AS businessunitid,

    -- Printer assignment (if PC has one from existing machines table)
    (SELECT printerid FROM machines WHERE machinenumber = p.machinenumber AND isactive = 1 LIMIT 1) AS printerid,

    -- Map coordinates (if exists from existing machines table)
    (SELECT mapleft FROM machines WHERE machinenumber = p.machinenumber AND isactive = 1 LIMIT 1) AS mapleft,
    (SELECT maptop FROM machines WHERE machinenumber = p.machinenumber AND isactive = 1 LIMIT 1) AS maptop,

    -- VNC (default no)
    0 AS isvnc,

    -- Location flags
    0 AS islocationonly,
    p.requires_manual_machine_config,

    -- Deprecated IP fields (set to NULL)
    NULL AS ipaddress1,
    NULL AS ipaddress2,

    -- Notes
    NULL AS machinenotes,

    -- Status and audit
    p.isactive,
    p.lastupdated,
    p.dateadded

FROM pc p
JOIN temp_pctype_mapping m ON p.pctypeid = m.pctypeid
WHERE p.isactive = 1;

SELECT CONCAT('✓ Prepared ', COUNT(*), ' PC records for migration') AS status
FROM temp_new_machines;

SELECT '' AS '';

-- =====================================================
-- STEP 5: Show sample of data to be migrated
-- =====================================================

SELECT 'Sample of PCs to be migrated (first 5):' AS '';
SELECT
    old_pcid,
    machinenumber,
    hostname,
    serialnumber,
    machinetypeid,
    osid,
    machinestatusid
FROM temp_new_machines
LIMIT 5;

SELECT '' AS '';

-- =====================================================
-- STEP 6: Insert PC records into machines table
-- =====================================================

SELECT 'Inserting PC records into machines table...' AS '';

INSERT INTO machines (
    machinetypeid,
    machinenumber,
    hostname,
    alias,
    loggedinuser,
    modelnumberid,
    controllertypeid,
    controllerosid,
    serialnumber,
    osid,
    machinestatusid,
    pctypeid,
    businessunitid,
    printerid,
    mapleft,
    maptop,
    isvnc,
    islocationonly,
    requires_manual_machine_config,
    ipaddress1,
    ipaddress2,
    machinenotes,
    isactive,
    lastupdated,
    dateadded
)
SELECT
    machinetypeid,
    machinenumber,
    hostname,
    alias,
    loggedinuser,
    modelnumberid,
    controllertypeid,
    controllerosid,
    serialnumber,
    osid,
    machinestatusid,
    pctypeid,
    businessunitid,
    printerid,
    mapleft,
    maptop,
    isvnc,
    islocationonly,
    requires_manual_machine_config,
    ipaddress1,
    ipaddress2,
    machinenotes,
    isactive,
    lastupdated,
    dateadded
FROM temp_new_machines;

SELECT CONCAT('✓ Inserted ', ROW_COUNT(), ' PC records into machines table') AS status;

SELECT '' AS '';

-- =====================================================
-- STEP 7: Create mapping table for old pcid to new machineid
-- =====================================================

DROP TABLE IF EXISTS pc_to_machine_id_mapping;
CREATE TABLE pc_to_machine_id_mapping (
    pcid INT,
    old_hostname VARCHAR(100),
    new_machineid INT,
    new_machinenumber VARCHAR(255),
    migration_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (pcid),
    KEY idx_new_machineid (new_machineid)
) ENGINE=InnoDB COMMENT='Mapping of old PC IDs to new machine IDs for Phase 2 migration';

INSERT INTO pc_to_machine_id_mapping (pcid, old_hostname, new_machineid, new_machinenumber)
SELECT
    p.pcid,
    p.hostname,
    m.machineid,
    m.machinenumber
FROM pc p
JOIN machines m ON m.hostname = p.hostname
WHERE p.isactive = 1
  AND m.pctypeid IS NOT NULL;  -- Only PCs (have pctypeid set)

SELECT CONCAT('✓ Created ID mapping table: ', COUNT(*), ' mappings') AS status
FROM pc_to_machine_id_mapping;

SELECT '' AS '';

-- =====================================================
-- VERIFICATION
-- =====================================================

SELECT '========================================' AS '';
SELECT 'MIGRATION VERIFICATION' AS '';
SELECT '========================================' AS '';
SELECT '' AS '';

-- Count machines before and after
SELECT 'Machine counts:' AS '';
SELECT
    'Original PCs (active)' AS category,
    COUNT(*) as count
FROM pc WHERE isactive = 1
UNION ALL
SELECT
    'New machines with pctypeid' AS category,
    COUNT(*) as count
FROM machines WHERE pctypeid IS NOT NULL
UNION ALL
SELECT
    'Total active machines now' AS category,
    COUNT(*) as count
FROM machines WHERE isactive = 1;

SELECT '' AS '';

-- Show machine type distribution
SELECT 'New machine type distribution:' AS '';
SELECT
    mt.machinetype,
    COUNT(*) as count
FROM machines m
JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
WHERE m.pctypeid IS NOT NULL
GROUP BY mt.machinetype
ORDER BY count DESC;

SELECT '' AS '';

-- Check for missing data
SELECT 'Data quality checks:' AS '';
SELECT
    'PCs with NULL hostname' AS check_name,
    COUNT(*) as count
FROM machines WHERE pctypeid IS NOT NULL AND hostname IS NULL
UNION ALL
SELECT
    'PCs with NULL machinetypeid' AS check_name,
    COUNT(*) as count
FROM machines WHERE pctypeid IS NOT NULL AND machinetypeid IS NULL
UNION ALL
SELECT
    'PCs with NULL machinestatusid' AS check_name,
    COUNT(*) as count
FROM machines WHERE pctypeid IS NOT NULL AND machinestatusid IS NULL;

SELECT '' AS '';

SELECT '✓ Script 01 completed successfully' AS status;
SELECT 'Next: Run script 02_migrate_network_interfaces_to_communications.sql' AS '';

SET SQL_SAFE_UPDATES = 1;

-- =====================================================
-- NOTES
-- =====================================================
-- Backup table created: pc_backup_phase2
-- Mapping table created: pc_to_machine_id_mapping
--
-- PCs migrated with:
-- - machinenumber = hostname
-- - alias = hostname
-- - Machine type based on PC type mapping
-- - All PC-specific fields populated
--
-- Next scripts will migrate:
-- - Network interfaces → communications
-- - Comm config → communications
-- - Warranties → warranties table
-- - Dualpath assignments → machinerelationships
--
-- ROLLBACK: Drop inserted records and restore from pc_backup_phase2
-- =====================================================
