CREATE TABLE IF NOT EXISTS devices (
    device_id VARCHAR(36) PRIMARY KEY,
    pc_name VARCHAR(64) NOT NULL,
    friend_code VARCHAR(64) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS friends (
    device_id_1 VARCHAR(36) NOT NULL,
    device_id_2 VARCHAR(36) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (device_id_1, device_id_2),
    FOREIGN KEY (device_id_1) REFERENCES devices(device_id) ON DELETE CASCADE,
    FOREIGN KEY (device_id_2) REFERENCES devices(device_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS servers (
    server_id VARCHAR(36) PRIMARY KEY,
    server_name VARCHAR(128) NOT NULL,
    owner_device_id VARCHAR(36) NOT NULL,
    active_host_device_id VARCHAR(36) DEFAULT NULL,
    status ENUM('offline', 'starting', 'online') NOT NULL DEFAULT 'offline',
    current_ip VARCHAR(45) DEFAULT NULL,
    last_heartbeat TIMESTAMP NULL DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (owner_device_id) REFERENCES devices(device_id) ON DELETE CASCADE,
    FOREIGN KEY (active_host_device_id) REFERENCES devices(device_id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS server_permissions (
    server_id VARCHAR(36) NOT NULL,
    device_id VARCHAR(36) NOT NULL,
    role VARCHAR(32) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (server_id, device_id),
    FOREIGN KEY (server_id) REFERENCES servers(server_id) ON DELETE CASCADE,
    FOREIGN KEY (device_id) REFERENCES devices(device_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
