package listing

import (
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"strconv"
	"strings"

	"hfb_sys/backend/internal/middleware"
	filemodule "hfb_sys/backend/internal/modules/file"
	"hfb_sys/backend/pkg/response"

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

type Handler struct {
	service *Service
	storage *filemodule.Storage
}

const maxExternalUploadBodyBytes = 256 * 1024

func NewHandler(service *Service, storage *filemodule.Storage) *Handler {
	return &Handler{service: service, storage: storage}
}

func (h *Handler) Create(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	var req CreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "发布信息不完整")
		return
	}
	item, err := h.service.Create(ownerID, req)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.Created(c, item)
}

func (h *Handler) ImportExternalUpload(c *gin.Context) {
	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxExternalUploadBodyBytes)
	raw, err := io.ReadAll(c.Request.Body)
	if err != nil {
		response.BadRequest(c, "上传内容过大或读取失败")
		return
	}
	var req ExternalUploadRequest
	if err := json.Unmarshal(raw, &req); err != nil {
		response.BadRequest(c, "上传 JSON 格式不正确")
		return
	}
	result, err := h.service.ImportExternalUpload(req, ExternalUploadMeta{
		IP:         c.ClientIP(),
		UserAgent:  c.GetHeader("User-Agent"),
		RawPayload: raw,
	})
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.Created(c, result)
}

func (h *Handler) DefaultUploadScreenshot(c *gin.Context) {
	c.Header("Content-Type", "image/svg+xml; charset=utf-8")
	c.Header("Cache-Control", "public, max-age=86400")
	c.String(http.StatusOK, `<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540"><rect width="960" height="540" fill="#f3f4f6"/><rect x="72" y="72" width="816" height="396" rx="24" fill="#ffffff" stroke="#d1d5db" stroke-width="4"/><text x="480" y="248" text-anchor="middle" font-family="Arial, sans-serif" font-size="42" font-weight="700" fill="#374151">账号资料默认图</text><text x="480" y="310" text-anchor="middle" font-family="Arial, sans-serif" font-size="28" fill="#6b7280">开放接口上传，待后台补充审核</text></svg>`)
}

func (h *Handler) Update(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req UpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "发布信息不完整")
		return
	}
	item, err := h.service.Update(ownerID, id, req)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) SubmitReview(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.SubmitReview(ownerID, id)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) ListPendingReview(c *gin.Context) {
	items, err := h.service.ListPendingReview()
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, gin.H{"items": items})
}

func (h *Handler) ListAdmin(c *gin.Context) {
	query, ok := parseAdminListQuery(c)
	if !ok {
		return
	}
	result, err := h.service.ListAdmin(query)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) FindAdmin(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.FindAdmin(id)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) AdminOffline(c *gin.Context) {
	h.adminAction(c, h.service.AdminOffline)
}

func (h *Handler) AdminMarkAbnormal(c *gin.Context) {
	h.adminAction(c, h.service.AdminMarkAbnormal)
}

func (h *Handler) adminAction(c *gin.Context, fn func(uint64, uint64, AdminActionRequest, AuditMeta) (*ListingDTO, error)) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req AdminActionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "操作原因不能为空")
		return
	}
	item, err := fn(adminID, id, req, auditMeta(c))
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func auditMeta(c *gin.Context) AuditMeta {
	return AuditMeta{
		IP:        c.ClientIP(),
		UserAgent: c.GetHeader("User-Agent"),
		RequestID: middleware.GetRequestID(c),
	}
}

func (h *Handler) Approve(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.Approve(id)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) AdjustReviewPrice(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req AdminPriceAdjustRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "调价参数不正确")
		return
	}
	item, err := h.service.AdjustReviewPrice(adminID, id, req, auditMeta(c))
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Reject(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	var req ReviewRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "审核拒绝原因不能为空")
		return
	}
	item, err := h.service.Reject(id, req)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Offline(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	if err := h.service.Offline(ownerID, id); err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, gin.H{"offline": true})
}

func (h *Handler) ListPublic(c *gin.Context) {
	items, err := h.service.ListPublic(parsePublicListQuery(c))
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, items)
}

func (h *Handler) FindPublic(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.FindPublic(id)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func (h *Handler) Cover(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	key, err := h.service.FindPublicCoverKey(id)
	if err != nil {
		writeListingError(c, err)
		return
	}
	h.writePublicObject(c, filemodule.ImageVariantFallbackKeys(key, filemodule.ImageVariantThumb)...)
}

func (h *Handler) Screenshot(c *gin.Context) {
	id, ok := parseID(c)
	if !ok {
		return
	}
	index, err := strconv.Atoi(c.Param("index"))
	if err != nil || index < 0 {
		response.BadRequest(c, "截图序号不正确")
		return
	}
	key, err := h.service.FindPublicScreenshotKey(id, index)
	if err != nil {
		writeListingError(c, err)
		return
	}
	h.writePublicObject(c, filemodule.ImageVariantFallbackKeys(key, filemodule.ImageVariantMedium)...)
}

func (h *Handler) writePublicObject(c *gin.Context, keys ...string) {
	if h.storage == nil {
		response.ServiceUnavailable(c, "文件存储未连接")
		return
	}
	var object *filemodule.Object
	for _, key := range keys {
		nextObject, err := h.storage.Get(c.Request.Context(), key)
		if err == nil {
			object = nextObject
			break
		}
	}
	if object == nil {
		response.Error(c, http.StatusNotFound, "not_found", "图片不存在或暂不可访问")
		return
	}
	defer func() {
		_ = object.Reader.Close()
	}()
	contentType := object.ContentType
	if contentType == "" {
		contentType = "application/octet-stream"
	}
	c.Header("Content-Type", contentType)
	c.Header("Cache-Control", "public, max-age=300")
	c.DataFromReader(http.StatusOK, object.Size, contentType, object.Reader, nil)
}

func (h *Handler) ListMine(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	items, err := h.service.ListMine(ownerID)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, gin.H{"items": items})
}

func (h *Handler) FindMine(c *gin.Context) {
	ownerID, ok := currentUserID(c)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	id, ok := parseID(c)
	if !ok {
		return
	}
	item, err := h.service.FindMine(ownerID, id)
	if err != nil {
		writeListingError(c, err)
		return
	}
	response.OK(c, item)
}

func currentUserID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextUserID)
	if !ok {
		return 0, false
	}
	userID, ok := value.(uint64)
	return userID, ok
}

func currentAdminID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextAdminID)
	if !ok {
		return 0, false
	}
	adminID, ok := value.(uint64)
	return adminID, ok
}

func parseID(c *gin.Context) (uint64, bool) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		response.BadRequest(c, "ID 不正确")
		return 0, false
	}
	return id, true
}

func parseAdminListQuery(c *gin.Context) (AdminListQuery, bool) {
	var query AdminListQuery
	if raw := c.Query("owner_id"); raw != "" {
		value, err := strconv.ParseUint(raw, 10, 64)
		if err != nil || value == 0 {
			response.BadRequest(c, "号主 ID 不正确")
			return query, false
		}
		query.OwnerID = value
	}
	if raw := c.Query("limit"); raw != "" {
		value, err := strconv.Atoi(raw)
		if err != nil || value <= 0 {
			response.BadRequest(c, "查询条数不正确")
			return query, false
		}
		query.Limit = value
	}
	if raw := c.Query("page"); raw != "" {
		value, err := strconv.Atoi(raw)
		if err != nil || value <= 0 {
			response.BadRequest(c, "页码不正确")
			return query, false
		}
		query.Page = value
	}
	if raw := c.Query("page_size"); raw != "" {
		value, err := strconv.Atoi(raw)
		if err != nil || value <= 0 {
			response.BadRequest(c, "每页条数不正确")
			return query, false
		}
		query.PageSize = value
	}
	query.Status = c.Query("status")
	query.ReviewStatus = c.Query("review_status")
	return query, true
}

func parsePublicListQuery(c *gin.Context) PublicListQuery {
	query := PublicListQuery{
		Page:           parsePositiveInt(c.DefaultQuery("page", "1"), 1),
		PageSize:       parsePositiveInt(c.DefaultQuery("page_size", "20"), 20),
		Keyword:        strings.TrimSpace(c.Query("keyword")),
		Sort:           strings.TrimSpace(c.Query("sort")),
		Zone:           strings.TrimSpace(c.Query("zone")),
		Server:         parseCSVQuery(c.Query("server")),
		Region:         parseCSVQuery(c.Query("region")),
		LoginMethod:    parseCSVQuery(firstNonEmpty(c.Query("login_method"), c.Query("login"))),
		Rank:           parseCSVQuery(c.Query("rank")),
		Insurance:      parseCSVQuery(c.Query("insurance")),
		Stamina:        parseCSVQuery(c.Query("stamina")),
		Load:           parseCSVQuery(c.Query("load")),
		SkinGroup:      parseCSVQuery(c.Query("skin_group")),
		SkinName:       parseCSVQuery(firstNonEmpty(c.Query("skin_name"), c.Query("skin"))),
		MinCoin:        parseOptionalFloat(c.Query("min_coin")),
		MaxCoin:        parseOptionalFloat(c.Query("max_coin")),
		MinPrice:       parseOptionalFloat(c.Query("min_price")),
		MaxPrice:       parseOptionalFloat(c.Query("max_price")),
		MinDeposit:     parseOptionalFloat(c.Query("min_deposit")),
		MaxDeposit:     parseOptionalFloat(c.Query("max_deposit")),
		MinTotal:       parseOptionalFloat(c.Query("min_total")),
		MaxTotal:       parseOptionalFloat(c.Query("max_total")),
		MinFireLevel:   parseOptionalFloat(c.Query("min_fire_level")),
		MaxFireLevel:   parseOptionalFloat(c.Query("max_fire_level")),
		MinSecretKD:    parseOptionalFloat(c.Query("min_secret_kd")),
		MaxSecretKD:    parseOptionalFloat(c.Query("max_secret_kd")),
		ResourceRanges: parseResourceRanges(c),
	}
	if query.PageSize > 50 {
		query.PageSize = 50
	}
	return query
}

func parsePositiveInt(value string, fallback int) int {
	parsed, err := strconv.Atoi(strings.TrimSpace(value))
	if err != nil || parsed <= 0 {
		return fallback
	}
	return parsed
}

func parseOptionalFloat(value string) *float64 {
	value = strings.TrimSpace(value)
	if value == "" {
		return nil
	}
	parsed, err := strconv.ParseFloat(value, 64)
	if err != nil {
		return nil
	}
	return &parsed
}

func parseCSVQuery(value string) []string {
	parts := strings.Split(value, ",")
	result := make([]string, 0, len(parts))
	seen := make(map[string]struct{}, len(parts))
	for _, part := range parts {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		if _, ok := seen[part]; ok {
			continue
		}
		seen[part] = struct{}{}
		result = append(result, part)
	}
	return result
}

func parseResourceRanges(c *gin.Context) map[string]NumberRange {
	ranges := make(map[string]NumberRange)
	for key, values := range c.Request.URL.Query() {
		if !strings.HasPrefix(key, "resource_") {
			continue
		}
		var resourceKey string
		var isMin bool
		switch {
		case strings.HasSuffix(key, "_min"):
			resourceKey = strings.TrimSuffix(strings.TrimPrefix(key, "resource_"), "_min")
			isMin = true
		case strings.HasSuffix(key, "_max"):
			resourceKey = strings.TrimSuffix(strings.TrimPrefix(key, "resource_"), "_max")
		default:
			continue
		}
		if resourceKey == "" || len(values) == 0 {
			continue
		}
		value := parseOptionalFloat(values[0])
		if value == nil {
			continue
		}
		numberRange := ranges[resourceKey]
		if isMin {
			numberRange.Min = value
		} else {
			numberRange.Max = value
		}
		ranges[resourceKey] = numberRange
	}
	return ranges
}

func firstNonEmpty(values ...string) string {
	for _, value := range values {
		if strings.TrimSpace(value) != "" {
			return value
		}
	}
	return ""
}

func writeListingError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrMissingTitle):
		response.BadRequest(c, "发布标题不能为空")
	case errors.Is(err, ErrMissingServerRegion):
		response.BadRequest(c, "请选择区服")
	case errors.Is(err, ErrInvalidPrice):
		response.BadRequest(c, "发布价格不正确")
	case errors.Is(err, ErrInvalidDeposit):
		response.BadRequest(c, "押金不能小于 0")
	case errors.Is(err, ErrDepositTooLow):
		response.BadRequest(c, "押金必须大于额外消耗品总价值")
	case errors.Is(err, ErrInvalidHafCoin):
		response.BadRequest(c, "哈夫币数量不正确")
	case errors.Is(err, ErrMissingScreenshot):
		response.BadRequest(c, "请至少上传一张账号截图")
	case errors.Is(err, ErrMissingUploaderName):
		response.BadRequest(c, "上传人名称不能为空")
	case errors.Is(err, ErrMissingUploadData):
		response.BadRequest(c, "上传账号数据不能为空")
	case errors.Is(err, ErrUploaderNotFound):
		response.BadRequest(c, "未匹配到可用后台用户")
	case errors.Is(err, ErrUploaderAmbiguous):
		response.BadRequest(c, "上传人名称匹配到多个后台用户，请使用唯一用户名")
	case errors.Is(err, ErrTooManyUploadItems):
		response.BadRequest(c, "单次上传账号数量过多")
	case isUploadValidationError(err):
		response.BadRequest(c, err.Error())
	case isFireLevelTooLow(err):
		var levelErr FireLevelTooLowError
		errors.As(err, &levelErr)
		response.BadRequest(c, "烽火等级低于"+strconv.Itoa(levelErr.Min)+"级的号无法发布")
	case errors.Is(err, ErrInvalidInput):
		response.BadRequest(c, "发布信息不符合规则")
	case errors.Is(err, ErrListingLocked):
		response.Error(c, http.StatusConflict, "listing_locked", "当前发布不可修改")
	case IsNotFound(err):
		response.Error(c, http.StatusNotFound, "not_found", "发布不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "发布服务暂时不可用")
	}
}

func isFireLevelTooLow(err error) bool {
	var levelErr FireLevelTooLowError
	return errors.As(err, &levelErr)
}

func isUploadValidationError(err error) bool {
	var validationErr UploadValidationError
	return errors.As(err, &validationErr)
}
