package admin

import (
	"context"
	"strings"

	"apps/backend/internal/module/member/domain"
	memberUC "apps/backend/internal/module/member/usecase"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *CreateMemberLogic) CreateMember(req *types.AdminCreateMemberReq) (resp *types.AdminCreateMemberData, err error) {
	tmp := req.Password
	if tmp == "" {
		tmp = memberUC.GenerateTempPassword()
	} else if err := memberUC.ValidatePasswordPolicy(tmp); err != nil {
		return nil, err
	}
	email := strings.ToLower(strings.TrimSpace(req.Email))
	m, _, err := l.svcCtx.Auth.CreateUserAccount(l.ctx, domain.CreateLoginUserRequest{
		LoginID: email, Platform: domain.PlatformPassword, AccountType: domain.AccountTypeEmail,
		Password: tmp, DisplayName: req.DisplayName, Email: email, Phone: req.Phone,
	})
	if err != nil {
		return nil, err
	}
	// admin-created: apply roles / verified / extra profile
	now := domain.NowNano()
	if len(req.Roles) > 0 {
		m.Roles = req.Roles
	}
	if req.EmailVerified {
		m.EmailVerified = true
		m.EmailVerifiedAt = &now
		m.Status = domain.StatusActive
	}
	if req.Bio != "" {
		m.Bio = req.Bio
	}
	if req.Nickname != "" {
		m.Nickname = req.Nickname
	}
	if req.FullName != "" {
		m.FullName = req.FullName
	}
	m.UpdatedAt = now
	if err := l.svcCtx.Members.UpdateMember(l.ctx, m); err != nil {
		return nil, err
	}
	ids, _ := l.svcCtx.Auth.ListIdentities(l.ctx, m.UID)
	return &types.AdminCreateMemberData{
		User:              *types.MemberFromModelWithIdentities(m, ids),
		TemporaryPassword: tmp,
	}, nil
}
