-- Check if the procedure exists, and create it only if it does not
DROP PROCEDURE IF EXISTS `seed_router_data`;

DELIMITER //

CREATE PROCEDURE seed_router_data()
BEGIN
    -- Insert Routers
    INSERT INTO routers (router_id, facility, router_alias, facility_aet, openvpn_ip, router_vm_primary_ip,
                         last_seen, vpn_status_code, disk_status_code, app_status_code, license_status, free_disk, total_disk, disk_usage) 
    VALUES
        ('RTR001', 'Main Hospital', 'MAIN_RAD', 'RTR_1', '10.8.0.101', '192.168.1.101', NOW(), 'VPN_CONNECTED', 'DISK_NORMAL', 'CONTAINER_RUNNING', 'active', 500000000000, 1000000000000, 50.00),
        ('RTR002', 'Emergency Center', 'ER_RAD', 'RTR_2', '10.8.0.102', '192.168.1.102', NOW(), 'VPN_DISCONNECTED', 'DISK_WARNING', 'CONTAINER_RUNNING', 'active', 400000000000, 1000000000000, 60.00),
        ('RTR003', 'Imaging Center', 'IMG_CENTER', 'RTR_3', '10.8.0.103', '192.168.1.103', NOW(), 'VPN_CONNECTED', 'DISK_NORMAL', 'CONTAINER_RUNNING', 'active', 600000000000, 1000000000000, 40.00)
    ON DUPLICATE KEY UPDATE id = id;

    -- Store Router IDs
    SET @router1_id = (SELECT id FROM routers WHERE router_id = 'RTR001');
    SET @router2_id = (SELECT id FROM routers WHERE router_id = 'RTR002');
    SET @router3_id = (SELECT id FROM routers WHERE router_id = 'RTR003');

    -- Insert Container Status
    INSERT INTO container_status (router_id, container_name, status_code, created_at, updated_at) 
    VALUES
        (@router1_id, 'router-cstore-scp', 'CONTAINER_RUNNING', NOW(), NOW()),
        (@router1_id, 'router-cstore-scu', 'CONTAINER_RUNNING', NOW(), NOW()),
        (@router2_id, 'router-cstore-scp', 'CONTAINER_RUNNING', NOW(), NOW()),
        (@router2_id, 'router-cstore-scu', 'CONTAINER_RUNNING', NOW(), NOW()),
        (@router3_id, 'router-cstore-scp', 'CONTAINER_RUNNING', NOW(), NOW())
    ON DUPLICATE KEY UPDATE id = id;

    -- Insert DICOM Study Overview
    INSERT INTO dicom_study_overview (
        router_id, study_instance_uid, patient_id, patient_name, 
        accession_number, study_date, modality, study_description, 
        series_instance_uid, procedure_code, referring_physician_name,
        study_status_code
    ) 
    VALUES
        (@router1_id, '1.2.840.113619.2.55.3.283116435.276.1543707218.134', 'P1', 'John Doe', 'ACC1234', '2024-03-15', 'CT', 'Chest CT', '1.2.840.113619.2.55.3.283116435.276.1543707219.135', 'CT001', 'Dr. Smith', 'idle'),
        (@router2_id, '1.2.840.113619.2.55.3.283116435.276.1543707218.136', 'P2', 'Jane Doe', 'ACC1235', '2024-03-15', 'MR', 'Brain MRI', '1.2.840.113619.2.55.3.283116435.276.1543707219.137', 'MR001', 'Dr. Johnson', 'idle')
    ON DUPLICATE KEY UPDATE id = id;

END //

DELIMITER ;

-- Automatically call the procedure after creation
CALL seed_router_data();
