package common

import (
	"context"
	"fmt"

	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/logger"
)

type GetDownloadLinkLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewGetDownloadLinkLogic 获取下载链接
func NewGetDownloadLinkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDownloadLinkLogic {
	return &GetDownloadLinkLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetDownloadLink 根据邀请码和平台动态生成下载链接
// 生成的链接格式: https://{host}/v1/common/client/download/file/{platform}-{version}-ic_{invite_code}.{ext}
// Nginx 会拦截此请求，将其映射到实际文件，并在 Content-Disposition 中设置带邀请码的文件名
func (l *GetDownloadLinkLogic) GetDownloadLink(req *types.GetDownloadLinkRequest) (resp *types.GetDownloadLinkResponse, err error) {
	// 1. 获取站点域名 (数据库配置通常会覆盖文件配置)
	host := l.svcCtx.Config.Site.Host
	if host == "" {
		// 保底域名
		host = "api.airoport.co"
	}

	// 2. 版本号 (后续可以从数据库或配置中读取)
	version := "1.0.0"

	// 3. 根据平台确定文件扩展名
	var ext string
	switch req.Platform {
	case "windows":
		ext = ".exe"
	case "mac":
		ext = ".dmg"
	case "android":
		ext = ".apk"
	case "ios":
		ext = ".ipa"
	default:
		ext = ".bin"
	}

	// 4. 构建文件名: Hi快VPN-平台-版本号[-ic_邀请码].扩展名
	const AppNamePrefix = "Hi快VPN"
	var filename string
	if req.InviteCode != "" {
		filename = fmt.Sprintf("%s-%s-%s-ic-%s%s", AppNamePrefix, req.Platform, version, req.InviteCode, ext)
	} else {
		filename = fmt.Sprintf("%s-%s-%s%s", AppNamePrefix, req.Platform, version, ext)
	}

	// 5. 构建完整 URL (Nginx 会拦截此路径进行虚拟更名处理)
	url := fmt.Sprintf("https://%s/v1/common/client/download/file/%s", host, filename)

	return &types.GetDownloadLinkResponse{
		Url: url,
	}, nil
}
