package controller

import (
	"net/http"
	"time"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/model"
	"metazone.cc/metalab/internal/session"

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

// SettingsController 个人设置控制器
type SettingsController struct {
	authService      profileProvider
	avatarService    avatarProvider
	auditService     auditSubmittable
	sessionMgr       sessionManager
	sessionCfg       sessionConfig
	levelSvc         taskCompleter
	energySvc        energyRenameHandler
	notifyPrefReader notifyPrefReader
}

// NewSettingsController 构造函数
func NewSettingsController(authService profileProvider, avatarService avatarProvider, auditService auditSubmittable, sessionMgr sessionManager, sessionCfg sessionConfig, levelSvc taskCompleter) *SettingsController {
	return &SettingsController{authService: authService, avatarService: avatarService, auditService: auditService, sessionMgr: sessionMgr, sessionCfg: sessionCfg, levelSvc: levelSvc}
}

// WithEnergyService 链式注入域能服务
func (sc *SettingsController) WithEnergyService(svc energyRenameHandler) *SettingsController {
	sc.energySvc = svc
	return sc
}

// SettingsPage 个人设置页面（需登录）
func (sc *SettingsController) SettingsPage(c *gin.Context) {
	uidVal, exists := c.Get("uid")
	if !exists {
		common.RedirectToLogin(c)
		return
	}
	uid := uidVal.(uint)

	tab := c.Param("tab")
	if tab != "profile" && tab != "account" && tab != "sessions" && tab != "energy" && tab != "favorites" && tab != "notify" {
		c.String(http.StatusNotFound, "页面不存在")
		return
	}

	user, err := sc.authService.GetProfile(uid)
	if err != nil || user == nil {
		c.String(http.StatusNotFound, "用户不存在")
		return
	}

	// 查询待审核类型（用于前端显示审核提示）
	pendingTypes, _ := sc.auditService.GetPendingTypes(uid)

	data := gin.H{
		"Title":        "个人设置",
		"ExtraCSS":     "/static/css/settings.css",
		"ActiveTab":    tab,
		"User":         user,
		"RoleName":     model.RoleDisplayNames[user.Role],
		"StatusName":   model.StatusDisplayNames[user.Status],
		"PendingTypes": pendingTypes,
		"AuditTypes":   model.AuditTypeNames,
	}

	// 登录管理 tab 需要额外数据
	if tab == "sessions" {
		sessions, _ := sc.sessionMgr.ListByUID(uid)
		if sessions == nil {
			sessions = []*session.Session{}
		}
		currentSID, _ := c.Cookie(common.SessionCookieName)
		// 解析每个 session 的设备信息
		type sessionView struct {
			*session.Session
			DeviceInfo session.DeviceInfo
			IsCurrent  bool
			TTLMinutes int // 剩余有效分钟数（仅非当前设备显示）
		}
		var views []sessionView
		for _, s := range sessions {
			timeout := sc.sessionCfg.GetIdleTimeout() // 临时会话超时（分钟）
			if s.RememberMe {
				timeout = sc.sessionCfg.GetRememberTimeout() // 记住我超时（分钟）
			}
			elapsed := int(time.Since(s.LastAccess).Minutes())
			ttl := timeout - elapsed
			if ttl < 0 {
				ttl = 0
			}
			views = append(views, sessionView{
				Session:    s,
				DeviceInfo: session.ParseUA(s.UserAgent),
				IsCurrent:  s.ID == currentSID,
				TTLMinutes: ttl,
			})
		}
		data["Sessions"] = views
		data["CurrentSID"] = currentSID
	}

	c.HTML(http.StatusOK, "settings/index.html", common.BuildPageData(c, data))
}
