package label

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent/contact"
	"wechat-api/ent/label"
	"wechat-api/ent/labelrelationship"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *DeleteLabelLogic) DeleteLabel(req *types.IDsReq) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	fmt.Printf("req.Ids: %+v", req.Ids)
	data, err := l.svcCtx.DB.LabelRelationship.Query().
		Where(
			labelrelationship.HasLabelsWith(
				label.IDIn(req.Ids...),
			),                                                // Filter by ID
			labelrelationship.OrganizationID(organizationId), // Additional filter by organizationId
			labelrelationship.HasContactsWith(
				contact.OrganizationIDEQ(organizationId),
				contact.DeletedAtIsNil(),
			),
		).
		Only(l.ctx)
	//if err != nil {
	//	return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	//}
	fmt.Printf("data: %+v", data)
	if data == nil {
		_, err := l.svcCtx.DB.Label.Delete().Where(label.IDIn(req.Ids...), label.OrganizationIDEQ(organizationId)).Exec(l.ctx)

		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}

		return &types.BaseMsgResp{Msg: errormsg.DeleteSuccess}, nil
	} else {
		err = errorx.NewDefaultError("标签已被使用，无法删除！")
		return nil, err
	}
}
