package flexCdn

import (
	"context"
	"github.com/go-nunu/nunu-layout-advanced/internal/model"
	"github.com/go-nunu/nunu-layout-advanced/internal/repository"
	"github.com/redis/go-redis/v9"
	"time"
)

type CdnRepository interface {
	GetCdn(ctx context.Context, id int64) (*model.Cdn, error)
	PutToken(ctx context.Context, token string) error
	GetToken(ctx context.Context) (string, error)
	GetUserId(ctx context.Context, username string) (int64, error)
	GetNodeClusterId(ctx context.Context, name string) (int64, error)
}

func NewCdnRepository(
	repository *repository.Repository,
) CdnRepository {
	return &cdnRepository{
		Repository: repository,
	}
}

type cdnRepository struct {
	*repository.Repository
}

func (r *cdnRepository) GetCdn(ctx context.Context, id int64) (*model.Cdn, error) {
	var cdn model.Cdn

	return &cdn, nil
}

const cdnTokenKey = "cdn:token"

func (r *cdnRepository) PutToken(ctx context.Context, token string) error {
	// 设置 token 的过期时间，例如 2 小时
	const expiration = 2 * time.Hour

	// 使用 Set 方法将 token 存入 Redis
	err := r.Rdb.Set(ctx, cdnTokenKey, token, expiration).Err()
	if err != nil {
		return err
	}
	return nil
}

// GetToken 从 Redis 中获取 CDN token
func (r *cdnRepository) GetToken(ctx context.Context) (string, error) {
	token, err := r.Rdb.Get(ctx, cdnTokenKey).Result()
	if err != nil {
		// 如果 token 不存在，redis.Nil 会被返回
		if err == redis.Nil {
			return "", nil // 或者返回一个特定的错误表示 token 不存在
		}
		return "", err
	}

	return token, nil
}

func (r *cdnRepository) GetUserId(ctx context.Context, username string) (int64, error)  {
	var id int64
	if err := r.DBWithName(ctx,"cdn").Table("cloud_users").
		Where("username = ?", username).
		Select("id").
		Find(&id).Error; err != nil {
		return 0, err
	}
	return id, nil

}

func (r *cdnRepository) GetNodeClusterId(ctx context.Context, name string) (int64, error) {
	var id int64
	return id, r.DBWithName(ctx,"cdn").Table("cloud_node_clusters").
		Where("name = ?", name).
		Select("id").
		Find(&id).Error
}
