package migrate

import (
	"github.com/pingcap/log"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

var _ = AddDBMigrateRecord(
	"202407021100",
	func(db *gorm.DB) error {
		restoreJobs := "CREATE TABLE IF NOT EXISTS `restore_jobs` (" +
			"  `id` varchar(255) NOT NULL," +
			"  `region` varchar(255) NOT NULL," +
			"  `restore_id` bigint(20) NULL," +
			"  `cluster_status_id` bigint(20) NULL," +
			"  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," +
			"  `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP," +
			"  `tenant_id` bigint(20) NOT NULL," +
			"  `project_id` bigint(20) NOT NULL," +
			"  `backup_id` varchar(255) NULL," +
			"  `backup_info` json NULL," +
			"  `backup_time` timestamp NULL," +
			"  `source_cluster_id` varchar(255) NULL," +
			"  `target_cluster_id` varchar(255) NULL," +
			"  `target_token` varchar(255) NULL," +
			"  `source_token` varchar(255) NULL," +
			"  `state` enum('pending','running','succeeded','failed') NOT NULL DEFAULT 'running'," +
			"  `created_by` varchar(255) NOT NULL," +
			"  `size_bytes` bigint(20) NOT NULL DEFAULT 0," +
			"  `progress` json NULL," +
			"  `error` text NULL," +
			"  PRIMARY KEY (`id`)," +
			"  INDEX `idx_created_at`(`created_at`)," +
			"  INDEX `idx_target_cluster_id` (`target_cluster_id`)," +
			"  INDEX `idx_restore_id`(`restore_id`)" +
			")"
		err := db.Exec(restoreJobs).Error
		if err != nil {
			log.Error("create table restore_jobs failed", zap.Error(err))
		}
		err = db.Exec("ALTER TABLE `backup_schedules` rename column `schedule_time` to `next_schedule_time`").Error
		if err != nil {
			log.Error("rename `schedule_time` to `next_schedule_time` failed", zap.Error(err))
		}
		return nil
	},
)
