package basic

import (
	"context"
	"time"

	"bsm/full/module/social/group/internal/impl"
	"bsm/full/module/social/group/internal/models"
	pb "bsm/full/module/social/group/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 创建群组
func Create(ctx context.Context, in *pb.GroupItem) (reply *pb.DataStatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	record := &models.GroupBasic{
		Name:          in.GetName(),
		Introduce:     in.GetIntroduce(),
		Avatar:        in.GetAvatar(),
		Notice:        in.GetNotice(),
		MemberLimit:   DefaultMemberLimit,
		EnableAnyJoin: DefaultEnableAnyJoin,
		MemberTotal:   1,
	}
	record.Identity = utils.UUID()
	record.PassportID = auth.ID
	record.PassportIdentity = auth.Identity

	err = impl.DBService.Create(&record).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	member := &models.GroupMember{
		GroupID:       record.ID,
		GroupIdentity: record.Identity,
		Role:          ROLE_CREATEOR,
	}

	member.PassportID = auth.ID
	member.PassportIdentity = auth.Identity

	err = impl.DBService.Create(&member).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.DataStatusReply{
		Data:    record.Identity,
		Timeseq: time.Now().UnixNano(),
	}, nil

}
