// Package app 提供移动端（H5/小程序）的 HTTP 处理器
// 包含个人客户认证、注册、微信绑定等功能的 Handler 实现
package app

import (
	"github.com/break/junhong_cmp_fiber/internal/service/personal_customer"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
	"github.com/gofiber/fiber/v2"
	"go.uber.org/zap"
)

// PersonalCustomerHandler 个人客户处理器
type PersonalCustomerHandler struct {
	service *personal_customer.Service
	logger  *zap.Logger
}

// NewPersonalCustomerHandler 创建个人客户处理器实例
func NewPersonalCustomerHandler(service *personal_customer.Service, logger *zap.Logger) *PersonalCustomerHandler {
	return &PersonalCustomerHandler{
		service: service,
		logger:  logger,
	}
}

// PersonalCustomerDTO 个人客户 DTO
type PersonalCustomerDTO struct {
	ID        uint   `json:"id"`
	Phone     string `json:"phone"`
	Nickname  string `json:"nickname"`
	AvatarURL string `json:"avatar_url"`
	WxOpenID  string `json:"wx_open_id"`
	Status    int    `json:"status"`
}

// UpdateProfileRequest 更新个人资料请求
type UpdateProfileRequest struct {
	Nickname  string `json:"nickname"`   // 昵称
	AvatarURL string `json:"avatar_url"` // 头像 URL
}

// UpdateProfile 更新个人资料
// PUT /api/c/v1/profile
func (h *PersonalCustomerHandler) UpdateProfile(c *fiber.Ctx) error {
	var req UpdateProfileRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	// 从 context 中获取当前登录的客户 ID
	customerID, ok := c.Locals("customer_id").(uint)
	if !ok {
		return errors.New(errors.CodeUnauthorized, "未找到客户信息")
	}

	if err := h.service.UpdateProfile(c.Context(), customerID, req.Nickname, req.AvatarURL); err != nil {
		h.logger.Error("更新个人资料失败",
			zap.Uint("customer_id", customerID),
			zap.Error(err),
		)
		return errors.Wrap(errors.CodeInternalError, err, "更新个人资料失败")
	}

	return response.Success(c, fiber.Map{
		"message": "更新成功",
	})
}

// GetProfile 获取个人资料
// GET /api/c/v1/profile
func (h *PersonalCustomerHandler) GetProfile(c *fiber.Ctx) error {
	// 从 context 中获取当前登录的客户 ID
	customerID, ok := c.Locals("customer_id").(uint)
	if !ok {
		return errors.New(errors.CodeUnauthorized, "未找到客户信息")
	}

	// 获取客户资料（包含主手机号）
	customer, phone, err := h.service.GetProfileWithPhone(c.Context(), customerID)
	if err != nil {
		h.logger.Error("获取个人资料失败",
			zap.Uint("customer_id", customerID),
			zap.Error(err),
		)
		return errors.Wrap(errors.CodeInternalError, err, "获取个人资料失败")
	}

	// 构造响应
	resp := &PersonalCustomerDTO{
		ID:        customer.ID,
		Phone:     phone, // 使用查询到的主手机号
		Nickname:  customer.Nickname,
		AvatarURL: customer.AvatarURL,
		WxOpenID:  customer.WxOpenID,
		Status:    customer.Status,
	}

	return response.Success(c, resp)
}
