package service

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

type CcService interface {
	GetCcList(ctx context.Context, req v1.CCListRequest) ([]v1.CCListResponse, error)
	EditCcState(ctx context.Context, req v1.CCStateRequest) error
}
func NewCcService(
    service *Service,
    ccRepository repository.CcRepository,
	webForwardingRep repository.WebForwardingRepository,
	cdn CdnService,
) CcService {
	return &ccService{
		Service:        service,
		ccRepository: ccRepository,
		webForwardingRep: webForwardingRep,
		cdn: cdn,
	}
}

type ccService struct {
	*Service
	ccRepository repository.CcRepository
	webForwardingRep repository.WebForwardingRepository
	cdn CdnService
}

func (s *ccService) GetCcList(ctx context.Context, req v1.CCListRequest) ([]v1.CCListResponse, error) {
	webData, err := s.webForwardingRep.GetWebForwarding(ctx, req.WebId)
	if err != nil {
		return nil, err
	}
	if webData.CdnWebId == 0 {
		return nil, fmt.Errorf("网站不存在")
	}
	ccList, err := s.ccRepository.GetCcList(ctx, int64(webData.CdnWebId))
	if err != nil {
		return nil, err
	}
	var res []v1.CCListResponse
	for _, v := range ccList {
		res = append(res, v1.CCListResponse{
			Value: v.Value,
			Type: v.Type,
			Reason: v.Reason,
			SourceURL: v.SourceURL,
			SourceUserAgent: v.SourceUserAgent,
			CreatedAt: time.Unix(v.CreatedAt, 0).Format("2006-01-02 15:04:05"),
			ExpiredAt: time.Unix(v.ExpiredAt, 0).Format("2006-01-02 15:04:05"),
		})
	}
	return res, nil
}

func (s *ccService) EditCcState(ctx context.Context, req v1.CCStateRequest) error {
	for _, v := range req.Ips {
		webData, err := s.webForwardingRep.GetWebForwarding(ctx, req.WebId)
		if err != nil {
			return err
		}
		if webData.CdnWebId == 0 {
			return fmt.Errorf("网站不存在")
		}
		ccId, err := s.ccRepository.GetCcId(ctx, int64(webData.CdnWebId), v)
		if err != nil {
			return err
		}
		if ccId == 0 {
			return fmt.Errorf("IP不存在")
		}
		err = s.cdn.DelIpItem(ctx, ccId, v, "", "", 2000000000)
		if err != nil {
			return err
		}

	}
	return nil
}