package models

import (
	"fmt"

	"code.gitea.io/gitea/modules/log"
	"xorm.io/xorm"
)

type CustomMigration struct {
	Description string
	Migrate     func(*xorm.Engine) error
}

type CustomMigrationStatic struct {
	Description string
	Migrate     func(*xorm.Engine, *xorm.Engine) error
}

var customMigrations = []CustomMigration{
	{"Custom v1 Topic struct change to support chinese", syncTopicStruct},
}

var customMigrationsStatic = []CustomMigrationStatic{
	{"Delete organization user history data ", deleteNotDisplayUser},
	{"update issue_fixed_rate to 1 if num_issues is 0 ", updateIssueFixedRate},
}

func MigrateCustom(x *xorm.Engine) {

	for _, m := range customMigrations {
		log.Info("Migration: %s", m.Description)
		if err := m.Migrate(x); err != nil {

			log.Error("Migration: %v", err)

		}
	}

}

func MigrateCustomStatic(x *xorm.Engine, static *xorm.Engine) {
	for _, m := range customMigrationsStatic {
		log.Info("Migration: %s", m.Description)
		if err := m.Migrate(x, static); err != nil {

			log.Error("Migration: %v", err)

		}
	}
}

func syncTopicStruct(x *xorm.Engine) error {

	query := "ALTER TABLE topic ALTER COLUMN name TYPE varchar(105);"

	_, err := x.Exec(query)
	return err
}

func deleteNotDisplayUser(x *xorm.Engine, static *xorm.Engine) error {

	querySQL := "select id,name from public.user where type=1"
	rows, err := x.Query(querySQL)
	if err != nil {
		log.Info("select db failed,err:", err)
		return err
	}

	for i, userRow := range rows {
		log.Info("delete zuzi user, i=" + fmt.Sprint(i) + " userName=" + string(userRow["name"]))
		deleteSql := "delete from user_business_analysis where id=" + string(userRow["id"]) + " and name='" + string(userRow["name"]) + "'"
		static.Exec(deleteSql)
	}

	return nil
}

func updateIssueFixedRate(x *xorm.Engine, static *xorm.Engine) error {
	updateSQL := "update  repo_statistic  set issue_fixed_rate=1.0 where num_issues=0"
	_, err := static.Exec(updateSQL)
	return err
}
