package flexCdn

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

type ProxyService interface {
	GetProxyId (ctx context.Context, cdnWebId int64) (int64, error)
	GetProxy (ctx context.Context, id int64) (*model.Proxy, error)
	GetProxyData (ctx context.Context, cdnWebId int64) (*model.Proxy, error)
	EditProxy (ctx context.Context, cdnWebId int64, req v1.ProxyProtocolJSON) error
}
func NewProxyService(
    service *service.Service,
	proxyRep flexCdn.ProxyRepository,
	cdn CdnService,

) ProxyService {
	return &proxyService{
		Service:        service,
		proxyRep: proxyRep,
		cdn: cdn,
	}
}

type proxyService struct {
	*service.Service
	proxyRep flexCdn.ProxyRepository
	cdn      CdnService
}

func (s *proxyService) GetProxyId (ctx context.Context, cdnWebId int64) (int64, error) {
	id, err := s.proxyRep.GetProxyId(ctx, cdnWebId)
	if err != nil {
		return 0, err
	}
	return id, nil
}

func (s *proxyService) GetProxy (ctx context.Context, id int64) (*model.Proxy, error) {
	res, err := s.proxyRep.GetProxy(ctx, id)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (s *proxyService) GetProxyData (ctx context.Context, cdnWebId int64) (*model.Proxy, error) {
	id,err := s.proxyRep.GetProxyId(ctx, cdnWebId)
	if err != nil {
		return nil, err
	}
	data, err := s.proxyRep.GetProxy(ctx, id)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (r *proxyService) EditProxy(ctx context.Context,cdnWebId int64, req v1.ProxyProtocolJSON) error {
	proxyData, err := r.GetProxyData(ctx, cdnWebId)
	if err != nil {
		return err
	}
	var reqJson []byte
	reqJson, err = json.Marshal(req)
	if err != nil {
		return err
	}
	var addHeaders []string
	err = json.Unmarshal([]byte(proxyData.AddHeaders), &addHeaders)
	if err != nil {
		return err
	}
	if err := r.cdn.EditProxy(ctx, v1.Proxy{
		AddHeaders: addHeaders,
		ReverseProxyId: proxyData.Id,
		RequestHostType: proxyData.RequestHostType,
		RequestHost: proxyData.RequestHost,
		RequestHostExcludingPort: proxyData.RequestHostExcludingPort,
		RequestURI: proxyData.RequestURI,
		StripPrefix: proxyData.StripPrefix,
		AutoFlush: proxyData.AutoFlush,
		ProxyProtocolJSON: reqJson,
		FollowRedirects: proxyData.FollowRedirects,
		Retry50X: proxyData.Retry50X,
		Retry40X: proxyData.Retry40X,
	}); err != nil {
		return err
	}
	return nil
}