CREATE TABLE IF NOT EXISTS tenant (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_code VARCHAR(64) NOT NULL,
    tenant_name VARCHAR(128) NOT 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_code (tenant_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

SET @tenant_code_column_exists = (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'tenant'
      AND COLUMN_NAME = 'tenant_code'
);
SET @add_tenant_code_sql = IF(
    @tenant_code_column_exists = 0,
    'ALTER TABLE tenant ADD COLUMN tenant_code VARCHAR(64) NULL AFTER id',
    'SELECT 1'
);
PREPARE stmt_add_tenant_code FROM @add_tenant_code_sql;
EXECUTE stmt_add_tenant_code;
DEALLOCATE PREPARE stmt_add_tenant_code;

UPDATE tenant
SET tenant_code = CONCAT('TENANT_', LPAD(id, 6, '0'))
WHERE tenant_code IS NULL OR tenant_code = '';

UPDATE tenant
SET tenant_code = 'TENANT_DEFAULT'
WHERE id = 1;

SET @tenant_code_index_exists = (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'tenant'
      AND INDEX_NAME = 'uk_tenant_code'
);
SET @add_tenant_code_index_sql = IF(
    @tenant_code_index_exists = 0,
    'ALTER TABLE tenant ADD UNIQUE KEY uk_tenant_code (tenant_code)',
    'SELECT 1'
);
PREPARE stmt_add_tenant_code_index FROM @add_tenant_code_index_sql;
EXECUTE stmt_add_tenant_code_index;
DEALLOCATE PREPARE stmt_add_tenant_code_index;

INSERT INTO tenant (id, tenant_code, tenant_name, status, is_deleted, created_by, updated_by)
VALUES (1, 'TENANT_DEFAULT', '默认单位主体', 'ENABLED', 0, 0, 0)
ON DUPLICATE KEY UPDATE
    tenant_code = VALUES(tenant_code),
    tenant_name = VALUES(tenant_name),
    status = VALUES(status);
