package flexCdn

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

type CcIpListRepository interface {
	GetCcIpList(ctx context.Context, serverId int64) ([]v1.CcIpListResponse, error)
	GetHttpWebId(ctx context.Context, serverId int64) (int64, error)
	GetIpListId(ctx context.Context, serverId int64,ipListType string) (int64,error)
	GetIpId(ctx context.Context, ipListId int64,ip string,sourceCategory string) (int64,error)
	GetCcIpCount(ctx context.Context,ipListId int64, ip string,sourceCategory string) (int64, error)

}

func NewCcIpListRepository(
	repository *repository.Repository,
) CcIpListRepository {
	return &ccIpListRepository{
		Repository: repository,
	}
}

type ccIpListRepository struct {
	*repository.Repository
}

func (r *ccIpListRepository) GetCcIpList(ctx context.Context, serverId int64) ([]v1.CcIpListResponse, error) {
	var req []v1.CcIpListResponse
	ipListId, err := r.GetIpListId(ctx, serverId,"white")
	if err != nil {
		return nil, err
	}
	return req, r.DBWithName(ctx,"cdn").Table("cloud_ip_items").Where("listId = ? AND sourceCategory = ? AND state = ?", ipListId, "cc", 1).Order("id desc").Select("value,type, reason").Scan(&req).Error
}

func (r *ccIpListRepository) GetHttpWebId(ctx context.Context, serverId int64) (int64, error) {
	var webId int64
	return webId, r.DBWithName(ctx,"cdn").Table("cloud_servers").Where("id = ?", serverId).Select("webId").Scan(&webId).Error
}

func (r *ccIpListRepository) GetIpListId(ctx context.Context, serverId int64,ipListType string) (int64,error) {
	var ipListId int64
	return ipListId, r.DBWithName(ctx,"cdn").Table("cloud_ip_lists").Where("serverId = ? AND type = ?", serverId,ipListType).Select("id").Scan(&ipListId).Error
}

func (r *ccIpListRepository) GetIpId(ctx context.Context, ipListId int64,ip string,sourceCategory string) (int64,error) {
	var ipId int64
	return ipId, r.DBWithName(ctx,"cdn").Table("cloud_ip_items").Where("listId = ? AND value = ? AND sourceCategory = ?", ipListId,ip,sourceCategory).Order("id desc").Limit(1).Select("id").Scan(&ipId).Error
}

func (r *ccIpListRepository) GetCcIpCount(ctx context.Context,ipListId int64, ip string,sourceCategory string) (int64, error) {
	var count int64
	return count, r.DBWithName(ctx,"cdn").Table("cloud_ip_items").Where("listId = ? AND value = ? AND sourceCategory = ? AND state = 1", ipListId,ip,sourceCategory).Count(&count).Error
}