package flexCdn

import (
	"context"
	"encoding/json"
	"github.com/go-nunu/nunu-layout-advanced/internal/model"
	"github.com/go-nunu/nunu-layout-advanced/internal/repository"
)

type ProxyRepository interface {
	// 获取反向代理ID
	GetProxyId(ctx context.Context, cndWebId int64) (int64, error)
	GetProxy(ctx context.Context, id int64) (*model.Proxy, error)
}

func NewProxyRepository(
	repository *repository.Repository,
) ProxyRepository {
	return &proxyRepository{
		Repository: repository,
	}
}

type proxyRepository struct {
	*repository.Repository
}

// 获取反向代理ID
func (r *proxyRepository) GetProxyId(ctx context.Context, cndWebId int64) (int64, error) {
	type ReverseProxy struct {
		IsOn bool
		IsPrior bool
		ReverseProxyId int64
	}
	var reverseProxyByte string
	if err := r.DBWithName(ctx,"cdn").WithContext(ctx).Table("cloud_servers").Where("id = ?", cndWebId).Select("reverseProxy").Scan(&reverseProxyByte).Error; err != nil {
		return 0, err
	}
	var proxyData ReverseProxy
	if reverseProxyByte != "" {
		if err := json.Unmarshal([]byte(reverseProxyByte), &proxyData); err != nil {
			return 0, err
		}
		return proxyData.ReverseProxyId, nil
	}

	return 0, nil

}

func (r *proxyRepository) GetProxy(ctx context.Context, id int64) (*model.Proxy, error) {
	var res model.Proxy
	if err := r.DBWithName(ctx,"cdn").Table("cloud_reverse_proxies").Where("id = ?", id).First(&res).Error; err != nil {
		return nil, err
	}
	return &res, nil

}
