package model

import (
	"context"
	"database/sql"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ AgentShortLinkModel = (*customAgentShortLinkModel)(nil)

type (
	// AgentShortLinkModel is an interface to be customized, add more methods here,
	// and implement the added methods in customAgentShortLinkModel.
	AgentShortLinkModel interface {
		agentShortLinkModel
		FindOneByInviteCodeTypeDelState(ctx context.Context, inviteCode sql.NullString, tp int64, delState int64) (*AgentShortLink, error)
	}

	customAgentShortLinkModel struct {
		*defaultAgentShortLinkModel
	}
)

// NewAgentShortLinkModel returns a model for the database table.
func NewAgentShortLinkModel(conn sqlx.SqlConn, c cache.CacheConf) AgentShortLinkModel {
	return &customAgentShortLinkModel{
		defaultAgentShortLinkModel: newAgentShortLinkModel(conn, c),
	}
}

func (m *customAgentShortLinkModel) FindOneByInviteCodeTypeDelState(ctx context.Context, inviteCode sql.NullString, tp int64, delState int64) (*AgentShortLink, error) {
	builder := m.SelectBuilder().
		Where("invite_code = ? AND type = ? AND del_state = ?", inviteCode, tp, delState).
		Limit(1)
	rows, err := m.FindAll(ctx, builder, "")
	if err != nil {
		return nil, errors.Wrapf(err, "query short link by invite_code failed")
	}
	if len(rows) == 0 {
		return nil, ErrNotFound
	}
	return rows[0], nil
}
