// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.

package dao

import (
	"context"
	"strings"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"

	"gorm.io/gen"
	"gorm.io/gen/field"

	"gorm.io/plugin/dbresolver"

	"github.com/flowline-io/flowbot/internal/store/model"
)

func newReview(db *gorm.DB, opts ...gen.DOOption) review {
	_review := review{}

	_review.reviewDo.UseDB(db, opts...)
	_review.reviewDo.UseModel(&model.Review{})

	tableName := _review.reviewDo.TableName()
	_review.ALL = field.NewAsterisk(tableName)
	_review.ID = field.NewInt64(tableName, "id")
	_review.UID = field.NewString(tableName, "uid")
	_review.Topic = field.NewString(tableName, "topic")
	_review.ObjectiveID = field.NewInt64(tableName, "objective_id")
	_review.Type = field.NewField(tableName, "type")
	_review.Rating = field.NewInt32(tableName, "rating")
	_review.CreatedAt = field.NewTime(tableName, "created_at")
	_review.UpdatedAt = field.NewTime(tableName, "updated_at")
	_review.Evaluations = reviewHasManyEvaluations{
		db: db.Session(&gorm.Session{}),

		RelationField: field.NewRelation("Evaluations", "model.ReviewEvaluation"),
	}

	_review.fillFieldMap()

	return _review
}

type review struct {
	reviewDo

	ALL         field.Asterisk
	ID          field.Int64
	UID         field.String
	Topic       field.String
	ObjectiveID field.Int64
	Type        field.Field
	Rating      field.Int32
	CreatedAt   field.Time
	UpdatedAt   field.Time
	Evaluations reviewHasManyEvaluations

	fieldMap map[string]field.Expr
}

func (r review) Table(newTableName string) *review {
	r.reviewDo.UseTable(newTableName)
	return r.updateTableName(newTableName)
}

func (r review) As(alias string) *review {
	r.reviewDo.DO = *(r.reviewDo.As(alias).(*gen.DO))
	return r.updateTableName(alias)
}

func (r *review) updateTableName(table string) *review {
	r.ALL = field.NewAsterisk(table)
	r.ID = field.NewInt64(table, "id")
	r.UID = field.NewString(table, "uid")
	r.Topic = field.NewString(table, "topic")
	r.ObjectiveID = field.NewInt64(table, "objective_id")
	r.Type = field.NewField(table, "type")
	r.Rating = field.NewInt32(table, "rating")
	r.CreatedAt = field.NewTime(table, "created_at")
	r.UpdatedAt = field.NewTime(table, "updated_at")

	r.fillFieldMap()

	return r
}

func (r *review) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
	_f, ok := r.fieldMap[fieldName]
	if !ok || _f == nil {
		return nil, false
	}
	_oe, ok := _f.(field.OrderExpr)
	return _oe, ok
}

func (r *review) fillFieldMap() {
	r.fieldMap = make(map[string]field.Expr, 9)
	r.fieldMap["id"] = r.ID
	r.fieldMap["uid"] = r.UID
	r.fieldMap["topic"] = r.Topic
	r.fieldMap["objective_id"] = r.ObjectiveID
	r.fieldMap["type"] = r.Type
	r.fieldMap["rating"] = r.Rating
	r.fieldMap["created_at"] = r.CreatedAt
	r.fieldMap["updated_at"] = r.UpdatedAt

}

func (r review) clone(db *gorm.DB) review {
	r.reviewDo.ReplaceConnPool(db.Statement.ConnPool)
	return r
}

func (r review) replaceDB(db *gorm.DB) review {
	r.reviewDo.ReplaceDB(db)
	return r
}

type reviewHasManyEvaluations struct {
	db *gorm.DB

	field.RelationField
}

func (a reviewHasManyEvaluations) Where(conds ...field.Expr) *reviewHasManyEvaluations {
	if len(conds) == 0 {
		return &a
	}

	exprs := make([]clause.Expression, 0, len(conds))
	for _, cond := range conds {
		exprs = append(exprs, cond.BeCond().(clause.Expression))
	}
	a.db = a.db.Clauses(clause.Where{Exprs: exprs})
	return &a
}

func (a reviewHasManyEvaluations) WithContext(ctx context.Context) *reviewHasManyEvaluations {
	a.db = a.db.WithContext(ctx)
	return &a
}

func (a reviewHasManyEvaluations) Session(session *gorm.Session) *reviewHasManyEvaluations {
	a.db = a.db.Session(session)
	return &a
}

func (a reviewHasManyEvaluations) Model(m *model.Review) *reviewHasManyEvaluationsTx {
	return &reviewHasManyEvaluationsTx{a.db.Model(m).Association(a.Name())}
}

type reviewHasManyEvaluationsTx struct{ tx *gorm.Association }

func (a reviewHasManyEvaluationsTx) Find() (result []*model.ReviewEvaluation, err error) {
	return result, a.tx.Find(&result)
}

func (a reviewHasManyEvaluationsTx) Append(values ...*model.ReviewEvaluation) (err error) {
	targetValues := make([]interface{}, len(values))
	for i, v := range values {
		targetValues[i] = v
	}
	return a.tx.Append(targetValues...)
}

func (a reviewHasManyEvaluationsTx) Replace(values ...*model.ReviewEvaluation) (err error) {
	targetValues := make([]interface{}, len(values))
	for i, v := range values {
		targetValues[i] = v
	}
	return a.tx.Replace(targetValues...)
}

func (a reviewHasManyEvaluationsTx) Delete(values ...*model.ReviewEvaluation) (err error) {
	targetValues := make([]interface{}, len(values))
	for i, v := range values {
		targetValues[i] = v
	}
	return a.tx.Delete(targetValues...)
}

func (a reviewHasManyEvaluationsTx) Clear() error {
	return a.tx.Clear()
}

func (a reviewHasManyEvaluationsTx) Count() int64 {
	return a.tx.Count()
}

type reviewDo struct{ gen.DO }

// GetByID
//
// SELECT * FROM @@table WHERE id=@id
func (r reviewDo) GetByID(id int) (result model.Review, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, id)
	generateSQL.WriteString("SELECT * FROM reviews WHERE id=? ")

	var executeSQL *gorm.DB
	executeSQL = r.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert
	err = executeSQL.Error

	return
}

// TakeByUidAndTopic query data by uid and topic and return one
//
// where("uid=@uid AND topic=@topic")
func (r reviewDo) TakeByUidAndTopic(uid string, topic string) (result model.Review, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, uid)
	params = append(params, topic)
	generateSQL.WriteString("uid=? AND topic=? ")

	var executeSQL *gorm.DB
	executeSQL = r.UnderlyingDB().Where(generateSQL.String(), params...).Take(&result) // ignore_security_alert
	err = executeSQL.Error

	return
}

// FindByUidAndTopic query data by uid and topic and return array
//
// where("uid=@uid AND topic=@topic")
func (r reviewDo) FindByUidAndTopic(uid string, topic string) (result []*model.Review, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, uid)
	params = append(params, topic)
	generateSQL.WriteString("uid=? AND topic=? ")

	var executeSQL *gorm.DB
	executeSQL = r.UnderlyingDB().Where(generateSQL.String(), params...).Find(&result) // ignore_security_alert
	err = executeSQL.Error

	return
}

func (r reviewDo) Debug() *reviewDo {
	return r.withDO(r.DO.Debug())
}

func (r reviewDo) WithContext(ctx context.Context) *reviewDo {
	return r.withDO(r.DO.WithContext(ctx))
}

func (r reviewDo) ReadDB() *reviewDo {
	return r.Clauses(dbresolver.Read)
}

func (r reviewDo) WriteDB() *reviewDo {
	return r.Clauses(dbresolver.Write)
}

func (r reviewDo) Session(config *gorm.Session) *reviewDo {
	return r.withDO(r.DO.Session(config))
}

func (r reviewDo) Clauses(conds ...clause.Expression) *reviewDo {
	return r.withDO(r.DO.Clauses(conds...))
}

func (r reviewDo) Returning(value interface{}, columns ...string) *reviewDo {
	return r.withDO(r.DO.Returning(value, columns...))
}

func (r reviewDo) Not(conds ...gen.Condition) *reviewDo {
	return r.withDO(r.DO.Not(conds...))
}

func (r reviewDo) Or(conds ...gen.Condition) *reviewDo {
	return r.withDO(r.DO.Or(conds...))
}

func (r reviewDo) Select(conds ...field.Expr) *reviewDo {
	return r.withDO(r.DO.Select(conds...))
}

func (r reviewDo) Where(conds ...gen.Condition) *reviewDo {
	return r.withDO(r.DO.Where(conds...))
}

func (r reviewDo) Order(conds ...field.Expr) *reviewDo {
	return r.withDO(r.DO.Order(conds...))
}

func (r reviewDo) Distinct(cols ...field.Expr) *reviewDo {
	return r.withDO(r.DO.Distinct(cols...))
}

func (r reviewDo) Omit(cols ...field.Expr) *reviewDo {
	return r.withDO(r.DO.Omit(cols...))
}

func (r reviewDo) Join(table schema.Tabler, on ...field.Expr) *reviewDo {
	return r.withDO(r.DO.Join(table, on...))
}

func (r reviewDo) LeftJoin(table schema.Tabler, on ...field.Expr) *reviewDo {
	return r.withDO(r.DO.LeftJoin(table, on...))
}

func (r reviewDo) RightJoin(table schema.Tabler, on ...field.Expr) *reviewDo {
	return r.withDO(r.DO.RightJoin(table, on...))
}

func (r reviewDo) Group(cols ...field.Expr) *reviewDo {
	return r.withDO(r.DO.Group(cols...))
}

func (r reviewDo) Having(conds ...gen.Condition) *reviewDo {
	return r.withDO(r.DO.Having(conds...))
}

func (r reviewDo) Limit(limit int) *reviewDo {
	return r.withDO(r.DO.Limit(limit))
}

func (r reviewDo) Offset(offset int) *reviewDo {
	return r.withDO(r.DO.Offset(offset))
}

func (r reviewDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *reviewDo {
	return r.withDO(r.DO.Scopes(funcs...))
}

func (r reviewDo) Unscoped() *reviewDo {
	return r.withDO(r.DO.Unscoped())
}

func (r reviewDo) Create(values ...*model.Review) error {
	if len(values) == 0 {
		return nil
	}
	return r.DO.Create(values)
}

func (r reviewDo) CreateInBatches(values []*model.Review, batchSize int) error {
	return r.DO.CreateInBatches(values, batchSize)
}

// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (r reviewDo) Save(values ...*model.Review) error {
	if len(values) == 0 {
		return nil
	}
	return r.DO.Save(values)
}

func (r reviewDo) First() (*model.Review, error) {
	if result, err := r.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*model.Review), nil
	}
}

func (r reviewDo) Take() (*model.Review, error) {
	if result, err := r.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*model.Review), nil
	}
}

func (r reviewDo) Last() (*model.Review, error) {
	if result, err := r.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*model.Review), nil
	}
}

func (r reviewDo) Find() ([]*model.Review, error) {
	result, err := r.DO.Find()
	return result.([]*model.Review), err
}

func (r reviewDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Review, err error) {
	buf := make([]*model.Review, 0, batchSize)
	err = r.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
		defer func() { results = append(results, buf...) }()
		return fc(tx, batch)
	})
	return results, err
}

func (r reviewDo) FindInBatches(result *[]*model.Review, batchSize int, fc func(tx gen.Dao, batch int) error) error {
	return r.DO.FindInBatches(result, batchSize, fc)
}

func (r reviewDo) Attrs(attrs ...field.AssignExpr) *reviewDo {
	return r.withDO(r.DO.Attrs(attrs...))
}

func (r reviewDo) Assign(attrs ...field.AssignExpr) *reviewDo {
	return r.withDO(r.DO.Assign(attrs...))
}

func (r reviewDo) Joins(fields ...field.RelationField) *reviewDo {
	for _, _f := range fields {
		r = *r.withDO(r.DO.Joins(_f))
	}
	return &r
}

func (r reviewDo) Preload(fields ...field.RelationField) *reviewDo {
	for _, _f := range fields {
		r = *r.withDO(r.DO.Preload(_f))
	}
	return &r
}

func (r reviewDo) FirstOrInit() (*model.Review, error) {
	if result, err := r.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*model.Review), nil
	}
}

func (r reviewDo) FirstOrCreate() (*model.Review, error) {
	if result, err := r.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*model.Review), nil
	}
}

func (r reviewDo) FindByPage(offset int, limit int) (result []*model.Review, count int64, err error) {
	result, err = r.Offset(offset).Limit(limit).Find()
	if err != nil {
		return
	}

	if size := len(result); 0 < limit && 0 < size && size < limit {
		count = int64(size + offset)
		return
	}

	count, err = r.Offset(-1).Limit(-1).Count()
	return
}

func (r reviewDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
	count, err = r.Count()
	if err != nil {
		return
	}

	err = r.Offset(offset).Limit(limit).Scan(result)
	return
}

func (r reviewDo) Scan(result interface{}) (err error) {
	return r.DO.Scan(result)
}

func (r reviewDo) Delete(models ...*model.Review) (result gen.ResultInfo, err error) {
	return r.DO.Delete(models)
}

func (r *reviewDo) withDO(do gen.Dao) *reviewDo {
	r.DO = *do.(*gen.DO)
	return r
}
