package http

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	"gitlink.org.cn/cloudream/common/pkgs/async"
	"gitlink.org.cn/cloudream/common/pkgs/logger"
	"gitlink.org.cn/cloudream/jcs-pub/client/internal/services"
	cliapi "gitlink.org.cn/cloudream/jcs-pub/client/sdk/api"
)

type ServerEventChan = async.UnboundChannel[ServerEvent]

type ServerEvent interface {
	IsServerEvent() bool
}

type ExitEvent struct {
	ServerEvent
	Err error
}

type Server struct {
	cfg       *Config
	httpSrv   *http.Server
	svc       *services.Service
	eventChan *ServerEventChan
}

func NewServer(cfg *Config, svc *services.Service) *Server {
	return &Server{
		cfg:       cfg,
		svc:       svc,
		eventChan: async.NewUnboundChannel[ServerEvent](),
	}
}

func (s *Server) Start() *ServerEventChan {
	go func() {
		if s.cfg == nil {
			return
		}

		engine := gin.New()
		s.httpSrv = &http.Server{
			Addr:    s.cfg.Listen,
			Handler: engine,
		}

		s.initRouters(engine)

		logger.Infof("start serving http at: %s", s.cfg.Listen)

		err := s.httpSrv.ListenAndServe()
		if err != nil {
			logger.Infof("http stopped with error: %s", err.Error())
		} else {
			logger.Infof("http stopped")
		}

		s.eventChan.Send(ExitEvent{Err: err})
	}()
	return s.eventChan
}

func (s *Server) Stop() {
	if s.httpSrv == nil {
		s.eventChan.Send(ExitEvent{})
		return
	}

	s.httpSrv.Shutdown(context.Background())
}

func (s *Server) initRouters(engine *gin.Engine) {
	rt := engine.Use()

	// initTemp(rt, s)

	s.routeV1(engine, rt)

	rt.GET(cliapi.ObjectListPathByPath, s.Object().ListByPath)
	rt.GET(cliapi.ObjectListByIDsPath, s.Object().ListByIDs)
	rt.GET(cliapi.ObjectDownloadPath, s.Object().Download)
	rt.GET(cliapi.ObjectDownloadByPathPath, s.Object().DownloadByPath)
	rt.POST(cliapi.ObjectUploadPath, s.Object().Upload)
	rt.GET(cliapi.ObjectGetPackageObjectsPath, s.Object().GetPackageObjects)
	rt.POST(cliapi.ObjectUpdateInfoPath, s.Object().UpdateInfo)
	rt.POST(cliapi.ObjectUpdateInfoByPathPath, s.Object().UpdateInfoByPath)
	rt.POST(cliapi.ObjectMovePath, s.Object().Move)
	rt.POST(cliapi.ObjectDeletePath, s.Object().Delete)
	rt.POST(cliapi.ObjectDeleteByPathPath, s.Object().DeleteByPath)
	rt.POST(cliapi.ObjectClonePath, s.Object().Clone)

	rt.GET(cliapi.PackageGetPath, s.Package().Get)
	rt.GET(cliapi.PackageGetByFullNamePath, s.Package().GetByFullName)
	rt.POST(cliapi.PackageCreatePath, s.Package().Create)
	rt.POST(cliapi.PackageCreateLoadPath, s.Package().CreateLoad)
	rt.POST(cliapi.PackageDeletePath, s.Package().Delete)
	rt.POST(cliapi.PackageClonePath, s.Package().Clone)
	rt.GET(cliapi.PackageListBucketPackagesPath, s.Package().ListBucketPackages)
	// rt.GET(cdsapi.PackageGetCachedStoragesPath, s.Package().GetCachedStorages)

	rt.POST(cliapi.UserSpaceLoadPackagePath, s.UserSpace().LoadPackage)
	rt.POST(cliapi.UserSpaceCreatePackagePath, s.UserSpace().CreatePackage)
	rt.GET(cliapi.UserSpaceGetPath, s.UserSpace().Get)

	// rt.POST(cdsapi.CacheMovePackagePath, s.Cache().MovePackage)

	rt.GET(cliapi.BucketGetByNamePath, s.Bucket().GetByName)
	rt.POST(cliapi.BucketCreatePath, s.Bucket().Create)
	rt.POST(cliapi.BucketDeletePath, s.Bucket().Delete)
	rt.GET(cliapi.BucketListAllPath, s.Bucket().ListAll)
}

func (s *Server) routeV1(eg *gin.Engine, rt gin.IRoutes) {
	v1 := eg.Group("/v1")

	awsAuth := NewAWSAuth(s.cfg)

	v1.GET(cliapi.ObjectListPathByPath, awsAuth.Auth, s.Object().ListByPath)
	v1.GET(cliapi.ObjectListByIDsPath, awsAuth.Auth, s.Object().ListByIDs)
	v1.GET(cliapi.ObjectDownloadPath, awsAuth.Auth, s.Object().Download)
	v1.GET(cliapi.ObjectDownloadByPathPath, awsAuth.Auth, s.Object().DownloadByPath)
	v1.POST(cliapi.ObjectUploadPath, awsAuth.AuthWithoutBody, s.Object().Upload)
	v1.GET(cliapi.ObjectGetPackageObjectsPath, awsAuth.Auth, s.Object().GetPackageObjects)
	v1.POST(cliapi.ObjectUpdateInfoPath, awsAuth.Auth, s.Object().UpdateInfo)
	v1.POST(cliapi.ObjectUpdateInfoByPathPath, awsAuth.Auth, s.Object().UpdateInfoByPath)
	v1.POST(cliapi.ObjectMovePath, awsAuth.Auth, s.Object().Move)
	v1.POST(cliapi.ObjectDeletePath, awsAuth.Auth, s.Object().Delete)
	v1.POST(cliapi.ObjectDeleteByPathPath, awsAuth.Auth, s.Object().DeleteByPath)
	v1.POST(cliapi.ObjectClonePath, awsAuth.Auth, s.Object().Clone)

	v1.GET(cliapi.PackageGetPath, awsAuth.Auth, s.Package().Get)
	v1.GET(cliapi.PackageGetByFullNamePath, awsAuth.Auth, s.Package().GetByFullName)
	v1.POST(cliapi.PackageCreatePath, awsAuth.Auth, s.Package().Create)
	v1.POST(cliapi.PackageCreateLoadPath, awsAuth.Auth, s.Package().CreateLoad)
	v1.POST(cliapi.PackageDeletePath, awsAuth.Auth, s.Package().Delete)
	v1.POST(cliapi.PackageClonePath, awsAuth.Auth, s.Package().Clone)
	v1.GET(cliapi.PackageListBucketPackagesPath, awsAuth.Auth, s.Package().ListBucketPackages)
	// v1.GET(cdsapi.PackageGetCachedStoragesPath, awsAuth.Auth, s.Package().GetCachedStorages)

	v1.POST(cliapi.UserSpaceLoadPackagePath, awsAuth.Auth, s.UserSpace().LoadPackage)
	v1.POST(cliapi.UserSpaceCreatePackagePath, awsAuth.Auth, s.UserSpace().CreatePackage)
	v1.GET(cliapi.UserSpaceGetPath, awsAuth.Auth, s.UserSpace().Get)
	rt.POST(cliapi.UserSpaceSpaceToSpacePath, s.UserSpace().SpaceToSpace)

	// v1.POST(cdsapi.CacheMovePackagePath, awsAuth.Auth, s.Cache().MovePackage)

	v1.GET(cliapi.BucketGetByNamePath, awsAuth.Auth, s.Bucket().GetByName)
	v1.POST(cliapi.BucketCreatePath, awsAuth.Auth, s.Bucket().Create)
	v1.POST(cliapi.BucketDeletePath, awsAuth.Auth, s.Bucket().Delete)
	v1.GET(cliapi.BucketListAllPath, awsAuth.Auth, s.Bucket().ListAll)

	rt.POST(cliapi.ObjectNewMultipartUploadPath, s.Object().NewMultipartUpload)
	rt.POST(cliapi.ObjectUploadPartPath, s.Object().UploadPart)
	rt.POST(cliapi.ObjectCompleteMultipartUploadPath, s.Object().CompleteMultipartUpload)

	rt.GET(cliapi.PresignedObjectListByPathPath, awsAuth.PresignedAuth, s.Presigned().ObjectListByPath)
	rt.GET(cliapi.PresignedObjectDownloadByPathPath, awsAuth.PresignedAuth, s.Presigned().ObjectDownloadByPath)
	rt.GET(cliapi.PresignedObjectDownloadPath, awsAuth.PresignedAuth, s.Presigned().ObjectDownload)
	rt.POST(cliapi.PresignedObjectUploadPath, awsAuth.PresignedAuth, s.Presigned().ObjectUpload)

	rt.POST(cliapi.PresignedObjectNewMultipartUploadPath, awsAuth.PresignedAuth, s.Presigned().ObjectNewMultipartUpload)
	rt.POST(cliapi.PresignedObjectUploadPartPath, awsAuth.PresignedAuth, s.Presigned().ObjectUploadPart)
	rt.POST(cliapi.PresignedObjectCompleteMultipartUploadPath, awsAuth.PresignedAuth, s.Presigned().ObjectCompleteMultipartUpload)

	// 不需要鉴权
	rt.GET(cliapi.MountDumpStatusPath, s.Mount().DumpStatus)
}
