package allocagent

import (
	"context"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/allocagent"
	"wechat-api/ent/predicate"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *DoAllocAgentLogic) DoAllocAgent(req *types.AllocAgentInfo) (*types.BaseMsgResp, error) {
	resp := types.BaseMsgResp{}

	if req.OrganizationId == nil && req.UserId == nil {
		return nil, errorx.NewInvalidArgumentError("租户ID和用户ID不能都为空")
	}

	var predicates []predicate.AllocAgent
	if req.UserId != nil && *req.UserId != "" {
		predicates = append(predicates, allocagent.UserIDEQ(*req.UserId))
	}
	if req.OrganizationId != nil && *req.OrganizationId > 0 {
		predicates = append(predicates, allocagent.OrganizationIDEQ(*req.OrganizationId))
	}
	_, err := l.svcCtx.DB.AllocAgent.Query().Where(predicates...).First(l.ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			_, err = l.svcCtx.DB.AllocAgent.Create().
				SetNotNilUserID(req.UserId).
				SetNotNilOrganizationID(req.OrganizationId).
				SetNotNilAgents(req.Agents).
				SetNotNilStatus(tea.Int(1)).
				Save(l.ctx)
			if err != nil {
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
			}
		} else {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
	} else {
		_, err = l.svcCtx.DB.AllocAgent.Update().
			SetNotNilAgents(req.Agents).
			Where(predicates...).
			Save(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
	}

	return &resp, err
}
