package core

import (
	"context"
	"fmt"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gorm.io/gorm"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PageResourceRangeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPageResourceRangeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PageResourceRangeLogic {
	return &PageResourceRangeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PageResourceRangeLogic) PageResourceRange(req *types.ResourceSpecReq) (resp *types.PageResult, err error) {
	if req.PageNum <= 0 || req.PageSize <= 0 {
		return nil, fmt.Errorf("invalid pagination parameters: PageNum=%d, PageSize=%d", req.PageNum, req.PageSize)
	}
	result := &types.PageResult{
		PageNum:  req.PageNum,
		PageSize: req.PageSize,
	}

	query := l.buildBaseQuery(req)
	if err := query.Count(&result.Total).Error; err != nil {
		return nil, fmt.Errorf("failed to count records: %w", err)
	}

	var specs []*models.TResourceSpec
	if err := query.Model(models.TResourceSpec{}).Preload("BaseResourceSpecs").
		Scopes(paginate(req.PageNum, req.PageSize)).
		Find(&specs).Error; err != nil {
		return nil, fmt.Errorf("failed to query resources: %w", err)
	}

	result.List = specs
	return result, nil
}

func (l *PageResourceRangeLogic) buildBaseQuery(req *types.ResourceSpecReq) *gorm.DB {
	query := l.svcCtx.DbEngin.Model(&models.TResourceSpec{}).
		Where("deleted_at IS NULL")

	if req.ClusterId != "" {
		query = query.Where("cluster_id = ?", req.ClusterId)
	}
	if req.Tag != "" {
		query = query.Where("tag = ?", req.Tag)
	}
	if req.Status != "" {
		query = query.Where("status = ?", req.Status)
	}
	if req.ChangeType != "" {
		query = query.Where("change_type = ?", req.ChangeType)
	}
	if req.Type != "" {
		query = query.Where("type = ?", req.Type)
	}
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}

	return query
}

func paginate(pageNum, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		offset := (pageNum - 1) * pageSize
		return db.Offset(offset).Limit(pageSize).Order("create_time DESC")
	}
}
