package account

import (
	"context"
	"time"

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

// 新增标签
func TagCreate(ctx context.Context, in *pb.TagItem) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	AUTH, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// Validate input
	if in.Name == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// Check if tag already exists
	var cnt int64
	err = impl.DBService.Model(&models.PassportTags{}).
		Where("passport_id = ? AND name = ?", AUTH.ID, in.Name).
		Count(&cnt).Error
	if err != nil {
		return nil, errcode.ErrDB
	}

	if cnt == 0 {
		// Create new tag
		record := &models.PassportTags{
			Name: in.Name,
			Icon: in.Icon,
		}
		record.Identity = utils.UUID()
		record.PassportID = AUTH.ID
		record.PassportIdentity = AUTH.Identity

		err = impl.DBService.Create(record).Error
		if err != nil {
			return nil, errcode.ErrDB
		}
	} else {
		// Update existing tag icon
		err = impl.DBService.Model(&models.PassportTags{}).
			Where("passport_id = ? AND name = ?", AUTH.ID, in.Name).
			Update("icon", in.Icon).Error
		if err != nil {
			return nil, errcode.ErrDB
		}
	}

	return &pb.StatusReply{
		Timeseq: time.Now().UnixMilli(),
	}, nil

}
