SET @has_ai_providers := (
  SELECT COUNT(*) FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'ai_providers'
);--> statement-breakpoint
SET @sql := IF(@has_ai_providers = 0, '
  CREATE TABLE `ai_providers` (
    `id` varchar(128) NOT NULL,
    `provider` enum(''zhipu'',''openai'',''gemini'',''custom'') NOT NULL,
    `base_url` varchar(512),
    `model` varchar(128) NOT NULL,
    `api_key_encrypted` text NOT NULL,
    `api_key_last4` varchar(4),
    `is_default` boolean NOT NULL DEFAULT false,
    `created_by` varchar(128),
    `updated_by` varchar(128),
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
  );
', 'SELECT 1');--> statement-breakpoint
PREPARE stmt FROM @sql;--> statement-breakpoint
EXECUTE stmt;--> statement-breakpoint
DEALLOCATE PREPARE stmt;--> statement-breakpoint

SET @has_ai_provider_idx := (
  SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'ai_providers'
    AND INDEX_NAME = 'ai_provider_idx'
);--> statement-breakpoint
SET @sql := IF(@has_ai_provider_idx = 0, 'CREATE INDEX `ai_provider_idx` ON `ai_providers` (`provider`);', 'SELECT 1');--> statement-breakpoint
PREPARE stmt FROM @sql;--> statement-breakpoint
EXECUTE stmt;--> statement-breakpoint
DEALLOCATE PREPARE stmt;--> statement-breakpoint

SET @has_ai_provider_default_idx := (
  SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'ai_providers'
    AND INDEX_NAME = 'ai_provider_default_idx'
);--> statement-breakpoint
SET @sql := IF(@has_ai_provider_default_idx = 0, 'CREATE INDEX `ai_provider_default_idx` ON `ai_providers` (`is_default`);', 'SELECT 1');--> statement-breakpoint
PREPARE stmt FROM @sql;--> statement-breakpoint
EXECUTE stmt;--> statement-breakpoint
DEALLOCATE PREPARE stmt;--> statement-breakpoint
