package sql

import (
	"context"
	"fmt"
	"time"

	"github.com/go-sql-driver/mysql"
	gormmysql "gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func ExecuteSqlWithUrl(ctx context.Context, dbUrl, userPrefix, password, tlsConfig string, port int32) error {
	config := mysql.NewConfig()
	config.Net = "tcp"
	if userPrefix == "" {
		config.User = "root"
	} else {
		config.User = userPrefix + ".root"
	}
	config.Addr = fmt.Sprintf("%s:%d", dbUrl, port)
	config.Passwd = password
	config.DBName = "test"
	config.ParseTime = true
	config.Timeout = 30 * time.Second
	config.ReadTimeout = 30 * time.Second
	config.WriteTimeout = 30 * time.Second
	config.Params = map[string]string{"charset": "utf8mb4"}
	config.Collation = "utf8mb4_bin"
	config.TLSConfig = tlsConfig

	db, err := gorm.Open(gormmysql.Open(config.FormatDSN()))
	if err != nil {
		return err
	}

	type Record struct {
		gorm.Model
		Foo string
	}

	db.WithContext(ctx)

	if err := db.AutoMigrate(&Record{}); err != nil {
		return err
	}

	if err := db.Create(&Record{Foo: "bar"}).Error; err != nil {
		return err
	}

	var r Record
	if err := db.Take(&r, 1).Error; err != nil {
		return err
	}

	return nil
}
