package example

import (
	"context"

	"kra/internal/biz/system"
	"kra/internal/data/model"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

const initOrderExaFile = system.InitOrderInternal + 1

type initExaFile struct{}

func NewInitExaFile() system.SubInitializer {
	return &initExaFile{}
}

func (i *initExaFile) MigrateTable(ctx context.Context) (context.Context, error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}
	return ctx, db.AutoMigrate(&model.ExaFileUploadAndDownload{})
}

func (i *initExaFile) TableCreated(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	return db.Migrator().HasTable(&model.ExaFileUploadAndDownload{})
}

func (i *initExaFile) InitializerName() string {
	return model.TableNameExaFileUploadAndDownload
}

func (i *initExaFile) InitializeData(ctx context.Context) (context.Context, error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}
	entities := []model.ExaFileUploadAndDownload{
		{Name: "10.png", URL: "https://qmplusimg.henrongyi.top/1576554439myAvatar.png", Tag: "png", Key: "158787308910.png"},
		{Name: "logo.png", URL: "https://qmplusimg.henrongyi.top/1576554439myAvatar.png", Tag: "png", Key: "1587973709logo.png"},
	}
	if err := db.Create(&entities).Error; err != nil {
		return ctx, errors.Wrap(err, model.TableNameExaFileUploadAndDownload+"表数据初始化失败!")
	}
	return ctx, nil
}

func (i *initExaFile) DataInserted(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	var count int64
	if err := db.Model(&model.ExaFileUploadAndDownload{}).Where("name = ? AND key = ?", "logo.png", "1587973709logo.png").Count(&count).Error; err != nil {
		return false
	}
	return count > 0
}
