/**
 * @author chengliang
 * @date 2026/1/13 10:54
 * @brief
 *
 **/

package hotupdate

import (
	"context"
	"fmt"
	"time"

	"github.com/kamva/mgm/v3"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// VersionService 版本信息服务
type TVersionDB struct {
	collection *mgm.Collection
}

func NewVersionService() *TVersionDB {
	return &TVersionDB{
		collection: mgm.Coll(&MVersionInfo{}),
	}
}

// Create 创建版本
func (s *TVersionDB) Create(version *MVersionInfo) error {
	// 检查是否存在相同版本
	existing, err := s.FindOne(bson.M{
		"project": version.Proj,
		"os":      version.Os,
		"version": version.Version,
	})

	if err == nil && existing != nil {
		return fmt.Errorf("版本 %s-%s-%s 已存在", version.Proj, version.Os, version.Version)
	}

	// 插入新版本
	return s.collection.Create(version)
}

// Update 更新版本
func (s *TVersionDB) Update(id string, updates map[string]interface{}) (*MVersionInfo, error) {
	objectID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return nil, fmt.Errorf("无效ID: %w", err)
	}

	// 查找并更新
	filter := bson.M{"_id": objectID}
	update := bson.M{"$set": updates}

	opts := options.FindOneAndUpdate().
		SetReturnDocument(options.After)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	var result MVersionInfo
	err = s.collection.FindOneAndUpdate(ctx, filter, update, opts).Decode(&result)
	if err != nil {
		return nil, fmt.Errorf("更新失败: %w", err)
	}

	return &result, nil
}

// Delete 删除版本
func (s *TVersionDB) Delete(id string) error {
	objectID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return fmt.Errorf("无效ID: %w", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	result, err := s.collection.DeleteOne(ctx, bson.M{"_id": objectID})
	if err != nil {
		return fmt.Errorf("删除失败: %w", err)
	}

	if result.DeletedCount == 0 {
		return fmt.Errorf("未找到记录")
	}

	return nil
}

// FindOne 查找单个版本
func (s *TVersionDB) FindOne(filter bson.M) (*MVersionInfo, error) {
	var result MVersionInfo
	err := s.collection.First(filter, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}

// Find 查找多个版本
func (s *TVersionDB) Find(filter bson.M, opts ...*options.FindOptions) ([]MVersionInfo, error) {
	var results []MVersionInfo
	err := s.collection.SimpleFind(&results, filter, opts...)
	return results, err
}

// ListByProjectAndOS 根据项目和系统列出版本
func (s *TVersionDB) ListByProjectAndOS(project, os string, page, size int64) ([]MVersionInfo, int64, error) {
	filter := bson.M{"project": project}
	if os != "" {
		filter["os"] = os
	}

	// 获取总数
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	total, err := s.collection.CountDocuments(ctx, filter)
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	opts := options.Find().
		SetSort(bson.M{"created_at": -1}). // 按版本降序
		SetSkip((page - 1) * size).
		SetLimit(size)

	results, err := s.Find(filter, opts)
	if err != nil {
		return nil, 0, err
	}

	return results, total, nil
}
