// Package personal_customer 提供个人客户资料管理的业务逻辑服务
package personal_customer

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/store/postgres"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// Service 个人客户服务
type Service struct {
	store      *postgres.PersonalCustomerStore
	phoneStore *postgres.PersonalCustomerPhoneStore
	logger     *zap.Logger
}

// NewService 创建个人客户服务实例
func NewService(
	store *postgres.PersonalCustomerStore,
	phoneStore *postgres.PersonalCustomerPhoneStore,
	logger *zap.Logger,
) *Service {
	return &Service{
		store:      store,
		phoneStore: phoneStore,
		logger:     logger,
	}
}

// UpdateProfile 更新个人资料
func (s *Service) UpdateProfile(ctx context.Context, customerID uint, nickname, avatarURL string) error {
	customer, err := s.store.GetByID(ctx, customerID)
	if err != nil {
		s.logger.Error("查询个人客户失败",
			zap.Uint("customer_id", customerID),
			zap.Error(err),
		)
		return errors.Wrap(errors.CodeInternalError, err, "查询个人客户失败")
	}

	// 更新资料
	if nickname != "" {
		customer.Nickname = nickname
	}
	if avatarURL != "" {
		customer.AvatarURL = avatarURL
	}

	if err := s.store.Update(ctx, customer); err != nil {
		s.logger.Error("更新个人资料失败",
			zap.Uint("customer_id", customerID),
			zap.Error(err),
		)
		return errors.Wrap(errors.CodeInternalError, err, "更新个人资料失败")
	}

	s.logger.Info("更新个人资料成功",
		zap.Uint("customer_id", customerID),
	)

	return nil
}

// GetProfileWithPhone 获取个人资料（包含主手机号）
func (s *Service) GetProfileWithPhone(ctx context.Context, customerID uint) (*model.PersonalCustomer, string, error) {
	// 获取客户信息
	customer, err := s.store.GetByID(ctx, customerID)
	if err != nil {
		s.logger.Error("查询个人客户失败",
			zap.Uint("customer_id", customerID),
			zap.Error(err),
		)
		return nil, "", errors.Wrap(errors.CodeInternalError, err, "查询个人客户失败")
	}

	// 获取主手机号
	phone := ""
	primaryPhone, err := s.phoneStore.GetPrimaryPhone(ctx, customerID)
	if err != nil {
		if err != gorm.ErrRecordNotFound {
			s.logger.Error("查询主手机号失败",
				zap.Uint("customer_id", customerID),
				zap.Error(err),
			)
			// 不返回错误，继续返回客户信息（手机号为空）
		}
	} else {
		phone = primaryPhone.Phone
	}

	return customer, phone, nil
}
