package app

import (
	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"
	"verification-platform-backend/internal/service"
	"verification-platform-backend/pkg/response"

	"github.com/gin-gonic/gin"
)

func SetupInfoRoutes(r *gin.RouterGroup) {
	r.GET("/info", handleAppGetInfo)
	r.GET("/check-update", handleAppCheckUpdate)
	r.GET("/announcements", handleAppGetAnnouncements)
}

func handleAppGetInfo(c *gin.Context) {
	appKey := c.Param("appKey")
	var app model.Application
	if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
		response.Error(c, 404, "应用不存在")
		return
	}

	if service.GetApplicationDisabledStatus(app.ID) {
		response.Error(c, 403, "该应用已被禁用")
		return
	}

	response.Success(c, gin.H{
		"id":                 app.ID,
		"name":               app.Name,
		"description":        app.Description,
		"icon_url":           app.IconURL,
		"status":             app.Status,
		"billing_type":       app.BillingType,
		"login_policy":       app.LoginPolicy,
		"max_devices":        app.MaxDevices,
		"multi_open_mode":    app.MultiOpenMode,
		"max_instances":      app.MaxInstances,
		"enable_trial":       app.EnableTrial,
		"trial_balance":      app.TrialBalance,
		"heartbeat_interval": app.HeartbeatInterval,
		"heartbeat_timeout":  app.HeartbeatTimeout,
	})
}

func handleAppCheckUpdate(c *gin.Context) {
	appKey := c.Param("appKey")
	var app model.Application
	if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
		response.Error(c, 404, "应用不存在")
		return
	}

	if service.GetApplicationDisabledStatus(app.ID) {
		response.Error(c, 403, "该应用已被禁用")
		return
	}

	clientVersion := c.Query("version")

	var latestVersion model.Version
	err := database.DB.Where("application_id = ? AND status = ?", app.ID, "active").Order("created_at DESC").Preload("Files").First(&latestVersion).Error

	if err != nil {
		response.Success(c, gin.H{
			"has_update":      false,
			"latest_version":  "",
			"download_url":    "",
			"update_notes":    "",
			"update_strategy": "",
			"update_method":   "",
			"files":           []interface{}{},
		})
		return
	}

	hasUpdate := clientVersion != latestVersion.Version
	if latestVersion.ForceUpdate {
		hasUpdate = true
	}

	files := make([]gin.H, len(latestVersion.Files))
	for i, f := range latestVersion.Files {
		files[i] = gin.H{
			"file_path":   f.FilePath,
			"file_name":   f.FileName,
			"file_size":   f.FileSize,
			"file_hash":   f.FileHash,
			"file_type":   f.FileType,
			"is_required": f.IsRequired,
		}
	}

	response.Success(c, gin.H{
		"has_update":      hasUpdate,
		"latest_version":  latestVersion.Version,
		"download_url":    latestVersion.FilePath,
		"file_size":       latestVersion.FileSize,
		"file_hash":       latestVersion.FileHash,
		"entry_file":      latestVersion.EntryFile,
		"update_notes":    latestVersion.Description,
		"update_strategy": latestVersion.UpdateStrategy,
		"update_method":   latestVersion.UpdateMethod,
		"min_version":     latestVersion.MinVersion,
		"changelog":       latestVersion.Changelog,
		"files":           files,
	})
}

func handleAppGetAnnouncements(c *gin.Context) {
	appKey := c.Param("appKey")
	var app model.Application
	if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
		response.Error(c, 404, "应用不存在")
		return
	}

	if service.GetApplicationDisabledStatus(app.ID) {
		response.Error(c, 403, "该应用已被禁用")
		return
	}

	var announcements []model.Announcement
	if err := database.DB.Where("application_id = ? AND status = ?", app.ID, "active").Order("is_top DESC, created_at DESC").Find(&announcements).Error; err != nil {
		response.Error(c, 500, "获取公告失败")
		return
	}

	result := make([]gin.H, len(announcements))
	for i, a := range announcements {
		result[i] = gin.H{
			"id":         a.ID,
			"title":      a.Title,
			"content":    a.Content,
			"type":       a.Type,
			"is_top":     a.IsTop,
			"created_at": a.CreatedAt,
		}
	}

	response.Success(c, result)
}
