package logic

import (
	"context"
	"fmt"

	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"
	"sundynix-micro-go/common/utils/hash"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *CreateUserLogic) CreateUser(in *system.CreateUserReq) (*system.CreateUserResp, error) {
	// 如果有 OpenId，先查是否已存在（社交登录场景：已有用户直接返回）
	if in.OpenId != "" {
		var existing sysModel.SundynixUser
		if err := l.svcCtx.DB.Where("open_id = ?", in.OpenId).First(&existing).Error; err == nil {
			// 用户已存在，更新 session_key 后直接返回
			if in.SessionKey != "" {
				l.svcCtx.DB.Model(&existing).Update("session_key", in.SessionKey)
			}
			return &system.CreateUserResp{User: convertUserToProto(&existing)}, nil
		}
	}

	// 如果有 Account，检查是否重复（后台创建用户场景：禁止重复）
	if in.Account != "" {
		var count int64
		l.svcCtx.DB.Model(&sysModel.SundynixUser{}).Where("account = ?", in.Account).Count(&count)
		if count > 0 {
			return nil, fmt.Errorf("账号 %s 已存在", in.Account)
		}
	}

	u := sysModel.SundynixUser{
		Name:       in.Name,
		Account:    in.Account,
		Phone:      in.Phone,
		OpenID:     in.OpenId,
		SessionKey: in.SessionKey,
		ClientID:   in.ClientId,
	}
	if in.Password != "" {
		u.Password = hash.BcryptHash(in.Password)
	}
	if err := l.svcCtx.DB.Create(&u).Error; err != nil {
		return nil, fmt.Errorf("创建用户失败: %w", err)
	}
	return &system.CreateUserResp{User: convertUserToProto(&u)}, nil
}
