package api

import (
	"easyaudioencode/internal/core/host"
	"net/http"
	"net/http/httputil"
	"net/url"

	"git.lnton.com/lnton/pkg/web"
	"github.com/gin-gonic/gin"
)

type HostAPI struct {
	uc *Usecase
}

func NewHostAPI(uc *Usecase) *HostAPI {
	return &HostAPI{
		uc: uc,
	}
}

func RegisterHostAPI(base gin.IRouter, uc *Usecase, handler ...gin.HandlerFunc) {
	api := NewHostAPI(uc)
	g := base.Group("/api", handler...)

	g.GET("/devices", web.WrapH(api.findDevices))
	g.GET("/channels", web.WrapH(api.findChannels))
	base.POST("/api/login", api.login)
}

// login 代理登录
//
// 登录会代理到Host的登录接口,鉴权也会使用Host的接口
func (ha *HostAPI) login(c *gin.Context) {
	target, _ := url.Parse(ha.uc.Conf.Plugin.HttpAPI + "/login")
	proxy := httputil.NewSingleHostReverseProxy(target)

	origDirector := proxy.Director
	proxy.Director = func(req *http.Request) {
		origDirector(req)
		// 保持原始方法、头、查询、体
		req.Method = c.Request.Method
		req.URL.Path = "/login"
		req.URL.RawQuery = c.Request.URL.RawQuery
		req.Header = c.Request.Header.Clone()
		req.Body = c.Request.Body
		req.Host = target.Host
	}

	proxy.ErrorHandler = func(rw http.ResponseWriter, r *http.Request, err error) {
		http.Error(rw, err.Error(), http.StatusBadGateway)
	}

	proxy.ServeHTTP(c.Writer, c.Request)
}

func (ha *HostAPI) findDevices(c *gin.Context, in *host.FindDevicesInput) (any, error) {
	// // 用于角色控制
	// in.Level = web.GetLevel(c)
	// in.Username = web.GetUsername(c)

	out, err := ha.uc.HostCore.FindDevices(c, in)
	if err != nil {
		return nil, err
	}

	// 构造返回的body
	return out, nil
}

func (ha *HostAPI) findChannels(c *gin.Context, in *host.FindChannelsInput) (any, error) {
	// // 用于角色控制
	// in.Level = web.GetLevel(c)
	// in.Username = web.GetUsername(c)

	out, err := ha.uc.HostCore.FindChannels(c, in)
	if err != nil {
		return nil, err
	}

	// 构造返回的body
	return out, nil
}
