package flexCdn

import (
	"context"
	v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
	"github.com/go-nunu/nunu-layout-advanced/internal/repository"
)

type CcRepository interface {
	GetCcList(ctx context.Context, serviceId int64) ([]v1.CCList, error)
	GetCcId(ctx context.Context, serviceId int64, ip string) (int64, error)
}

func NewCcRepository(
	repository *repository.Repository,
) CcRepository {
	return &ccRepository{
		Repository: repository,
	}
}

type ccRepository struct {
	*repository.Repository
}

func (r *ccRepository) GetCcList(ctx context.Context, serviceId int64) ([]v1.CCList, error) {
	var req []v1.CCList
	if err := r.DBWithName(ctx,"cdn").Table("cloud_ip_items").Where("sourceServerId = ? AND state = 1", serviceId).Select("value,type,reason,sourceURL,sourceUserAgent,createdAt,expiredAt").Scan(&req).Error; err != nil {
		return nil, err
	}
	return req, nil
}

func (r *ccRepository) GetCcId(ctx context.Context, serviceId int64, ip string) (int64, error) {
	var req int64
	if err := r.DBWithName(ctx,"cdn").Table("cloud_ip_items").Where("sourceServerId = ? AND value = ? AND state = 1", serviceId, ip).Select("id").Scan(&req).Error; err != nil {
		return 0, err
	}
	return req, nil
}