CREATE TABLE IF NOT EXISTS enterprise (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    enterprise_name VARCHAR(128) NOT NULL,
    enterprise_url VARCHAR(255) DEFAULT NULL,
    logo_url VARCHAR(512) DEFAULT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'ENABLED',
    is_deleted TINYINT(1) NOT NULL DEFAULT 0,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_tenant_enterprise_name (tenant_id, enterprise_name),
    KEY idx_tenant_status (tenant_id, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

SET @project_enterprise_id_exists = (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'project'
      AND COLUMN_NAME = 'enterprise_id'
);
SET @add_project_enterprise_id_sql = IF(
    @project_enterprise_id_exists = 0,
    'ALTER TABLE project ADD COLUMN enterprise_id BIGINT UNSIGNED NULL AFTER project_name',
    'SELECT 1'
);
PREPARE stmt_add_project_enterprise_id FROM @add_project_enterprise_id_sql;
EXECUTE stmt_add_project_enterprise_id;
DEALLOCATE PREPARE stmt_add_project_enterprise_id;

SET @project_enterprise_idx_exists = (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'project'
      AND INDEX_NAME = 'idx_tenant_enterprise'
);
SET @add_project_enterprise_idx_sql = IF(
    @project_enterprise_idx_exists = 0,
    'ALTER TABLE project ADD KEY idx_tenant_enterprise (tenant_id, enterprise_id)',
    'SELECT 1'
);
PREPARE stmt_add_project_enterprise_idx FROM @add_project_enterprise_idx_sql;
EXECUTE stmt_add_project_enterprise_idx;
DEALLOCATE PREPARE stmt_add_project_enterprise_idx;
