package svc

import (
	fileModel "sundynix-micro-go/app/file/model"
	"sundynix-micro-go/app/file/rpc/internal/config"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config      config.Config
	DB          *gorm.DB
	MinioClient *minio.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	// 初始化GORM
	db, err := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{})
	if err != nil {
		logx.Errorf("连接数据库失败: %v", err)
		panic(err)
	}
	// 自动迁移
	if err := db.AutoMigrate(
		&fileModel.SundynixOss{},
		&fileModel.StorageConfig{},
	); err != nil {
		logx.Errorf("数据库迁移失败: %v", err)
	}

	// 初始化MinIO客户端
	minioClient, err := minio.New(c.Minio.Endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(c.Minio.AccessKeyId, c.Minio.AccessKeySecret, ""),
		Secure: c.Minio.UseSsl,
	})
	if err != nil {
		logx.Errorf("初始化MinIO客户端失败: %v", err)
		panic(err)
	}

	return &ServiceContext{
		Config:      c,
		DB:          db,
		MinioClient: minioClient,
	}
}
