// 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 query

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/0xJacky/Nginx-UI/model"
)

func newCert(db *gorm.DB, opts ...gen.DOOption) cert {
	_cert := cert{}

	_cert.certDo.UseDB(db, opts...)
	_cert.certDo.UseModel(&model.Cert{})

	tableName := _cert.certDo.TableName()
	_cert.ALL = field.NewAsterisk(tableName)
	_cert.ID = field.NewInt(tableName, "id")
	_cert.CreatedAt = field.NewTime(tableName, "created_at")
	_cert.UpdatedAt = field.NewTime(tableName, "updated_at")
	_cert.DeletedAt = field.NewField(tableName, "deleted_at")
	_cert.Name = field.NewString(tableName, "name")
	_cert.Domains = field.NewField(tableName, "domains")
	_cert.Filename = field.NewString(tableName, "filename")
	_cert.SSLCertificatePath = field.NewString(tableName, "ssl_certificate_path")
	_cert.SSLCertificateKeyPath = field.NewString(tableName, "ssl_certificate_key_path")
	_cert.AutoCert = field.NewInt(tableName, "auto_cert")
	_cert.ChallengeMethod = field.NewString(tableName, "challenge_method")
	_cert.DnsCredentialID = field.NewInt(tableName, "dns_credential_id")
	_cert.ACMEUserID = field.NewInt(tableName, "acme_user_id")
	_cert.KeyType = field.NewString(tableName, "key_type")
	_cert.Log = field.NewString(tableName, "log")
	_cert.Resource = field.NewField(tableName, "resource")
	_cert.SyncNodeIds = field.NewField(tableName, "sync_node_ids")
	_cert.MustStaple = field.NewBool(tableName, "must_staple")
	_cert.LegoDisableCNAMESupport = field.NewBool(tableName, "lego_disable_cname_support")
	_cert.DnsCredential = certBelongsToDnsCredential{
		db: db.Session(&gorm.Session{}),

		RelationField: field.NewRelation("DnsCredential", "model.DnsCredential"),
	}

	_cert.ACMEUser = certBelongsToACMEUser{
		db: db.Session(&gorm.Session{}),

		RelationField: field.NewRelation("ACMEUser", "model.AcmeUser"),
	}

	_cert.fillFieldMap()

	return _cert
}

type cert struct {
	certDo

	ALL                     field.Asterisk
	ID                      field.Int
	CreatedAt               field.Time
	UpdatedAt               field.Time
	DeletedAt               field.Field
	Name                    field.String
	Domains                 field.Field
	Filename                field.String
	SSLCertificatePath      field.String
	SSLCertificateKeyPath   field.String
	AutoCert                field.Int
	ChallengeMethod         field.String
	DnsCredentialID         field.Int
	ACMEUserID              field.Int
	KeyType                 field.String
	Log                     field.String
	Resource                field.Field
	SyncNodeIds             field.Field
	MustStaple              field.Bool
	LegoDisableCNAMESupport field.Bool
	DnsCredential           certBelongsToDnsCredential

	ACMEUser certBelongsToACMEUser

	fieldMap map[string]field.Expr
}

func (c cert) Table(newTableName string) *cert {
	c.certDo.UseTable(newTableName)
	return c.updateTableName(newTableName)
}

func (c cert) As(alias string) *cert {
	c.certDo.DO = *(c.certDo.As(alias).(*gen.DO))
	return c.updateTableName(alias)
}

func (c *cert) updateTableName(table string) *cert {
	c.ALL = field.NewAsterisk(table)
	c.ID = field.NewInt(table, "id")
	c.CreatedAt = field.NewTime(table, "created_at")
	c.UpdatedAt = field.NewTime(table, "updated_at")
	c.DeletedAt = field.NewField(table, "deleted_at")
	c.Name = field.NewString(table, "name")
	c.Domains = field.NewField(table, "domains")
	c.Filename = field.NewString(table, "filename")
	c.SSLCertificatePath = field.NewString(table, "ssl_certificate_path")
	c.SSLCertificateKeyPath = field.NewString(table, "ssl_certificate_key_path")
	c.AutoCert = field.NewInt(table, "auto_cert")
	c.ChallengeMethod = field.NewString(table, "challenge_method")
	c.DnsCredentialID = field.NewInt(table, "dns_credential_id")
	c.ACMEUserID = field.NewInt(table, "acme_user_id")
	c.KeyType = field.NewString(table, "key_type")
	c.Log = field.NewString(table, "log")
	c.Resource = field.NewField(table, "resource")
	c.SyncNodeIds = field.NewField(table, "sync_node_ids")
	c.MustStaple = field.NewBool(table, "must_staple")
	c.LegoDisableCNAMESupport = field.NewBool(table, "lego_disable_cname_support")

	c.fillFieldMap()

	return c
}

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

func (c *cert) fillFieldMap() {
	c.fieldMap = make(map[string]field.Expr, 21)
	c.fieldMap["id"] = c.ID
	c.fieldMap["created_at"] = c.CreatedAt
	c.fieldMap["updated_at"] = c.UpdatedAt
	c.fieldMap["deleted_at"] = c.DeletedAt
	c.fieldMap["name"] = c.Name
	c.fieldMap["domains"] = c.Domains
	c.fieldMap["filename"] = c.Filename
	c.fieldMap["ssl_certificate_path"] = c.SSLCertificatePath
	c.fieldMap["ssl_certificate_key_path"] = c.SSLCertificateKeyPath
	c.fieldMap["auto_cert"] = c.AutoCert
	c.fieldMap["challenge_method"] = c.ChallengeMethod
	c.fieldMap["dns_credential_id"] = c.DnsCredentialID
	c.fieldMap["acme_user_id"] = c.ACMEUserID
	c.fieldMap["key_type"] = c.KeyType
	c.fieldMap["log"] = c.Log
	c.fieldMap["resource"] = c.Resource
	c.fieldMap["sync_node_ids"] = c.SyncNodeIds
	c.fieldMap["must_staple"] = c.MustStaple
	c.fieldMap["lego_disable_cname_support"] = c.LegoDisableCNAMESupport

}

func (c cert) clone(db *gorm.DB) cert {
	c.certDo.ReplaceConnPool(db.Statement.ConnPool)
	return c
}

func (c cert) replaceDB(db *gorm.DB) cert {
	c.certDo.ReplaceDB(db)
	return c
}

type certBelongsToDnsCredential struct {
	db *gorm.DB

	field.RelationField
}

func (a certBelongsToDnsCredential) Where(conds ...field.Expr) *certBelongsToDnsCredential {
	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 certBelongsToDnsCredential) WithContext(ctx context.Context) *certBelongsToDnsCredential {
	a.db = a.db.WithContext(ctx)
	return &a
}

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

func (a certBelongsToDnsCredential) Model(m *model.Cert) *certBelongsToDnsCredentialTx {
	return &certBelongsToDnsCredentialTx{a.db.Model(m).Association(a.Name())}
}

type certBelongsToDnsCredentialTx struct{ tx *gorm.Association }

func (a certBelongsToDnsCredentialTx) Find() (result *model.DnsCredential, err error) {
	return result, a.tx.Find(&result)
}

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

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

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

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

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

type certBelongsToACMEUser struct {
	db *gorm.DB

	field.RelationField
}

func (a certBelongsToACMEUser) Where(conds ...field.Expr) *certBelongsToACMEUser {
	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 certBelongsToACMEUser) WithContext(ctx context.Context) *certBelongsToACMEUser {
	a.db = a.db.WithContext(ctx)
	return &a
}

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

func (a certBelongsToACMEUser) Model(m *model.Cert) *certBelongsToACMEUserTx {
	return &certBelongsToACMEUserTx{a.db.Model(m).Association(a.Name())}
}

type certBelongsToACMEUserTx struct{ tx *gorm.Association }

func (a certBelongsToACMEUserTx) Find() (result *model.AcmeUser, err error) {
	return result, a.tx.Find(&result)
}

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

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

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

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

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

type certDo struct{ gen.DO }

// FirstByID Where("id=@id")
func (c certDo) FirstByID(id int) (result *model.Cert, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, id)
	generateSQL.WriteString("id=? ")

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

	return
}

// DeleteByID update @@table set deleted_at=strftime('%Y-%m-%d %H:%M:%S','now') where id=@id
func (c certDo) DeleteByID(id int) (err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, id)
	generateSQL.WriteString("update certs set deleted_at=strftime('%Y-%m-%d %H:%M:%S','now') where id=? ")

	var executeSQL *gorm.DB
	executeSQL = c.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert
	err = executeSQL.Error

	return
}

func (c certDo) Debug() *certDo {
	return c.withDO(c.DO.Debug())
}

func (c certDo) WithContext(ctx context.Context) *certDo {
	return c.withDO(c.DO.WithContext(ctx))
}

func (c certDo) ReadDB() *certDo {
	return c.Clauses(dbresolver.Read)
}

func (c certDo) WriteDB() *certDo {
	return c.Clauses(dbresolver.Write)
}

func (c certDo) Session(config *gorm.Session) *certDo {
	return c.withDO(c.DO.Session(config))
}

func (c certDo) Clauses(conds ...clause.Expression) *certDo {
	return c.withDO(c.DO.Clauses(conds...))
}

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

func (c certDo) Not(conds ...gen.Condition) *certDo {
	return c.withDO(c.DO.Not(conds...))
}

func (c certDo) Or(conds ...gen.Condition) *certDo {
	return c.withDO(c.DO.Or(conds...))
}

func (c certDo) Select(conds ...field.Expr) *certDo {
	return c.withDO(c.DO.Select(conds...))
}

func (c certDo) Where(conds ...gen.Condition) *certDo {
	return c.withDO(c.DO.Where(conds...))
}

func (c certDo) Order(conds ...field.Expr) *certDo {
	return c.withDO(c.DO.Order(conds...))
}

func (c certDo) Distinct(cols ...field.Expr) *certDo {
	return c.withDO(c.DO.Distinct(cols...))
}

func (c certDo) Omit(cols ...field.Expr) *certDo {
	return c.withDO(c.DO.Omit(cols...))
}

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

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

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

func (c certDo) Group(cols ...field.Expr) *certDo {
	return c.withDO(c.DO.Group(cols...))
}

func (c certDo) Having(conds ...gen.Condition) *certDo {
	return c.withDO(c.DO.Having(conds...))
}

func (c certDo) Limit(limit int) *certDo {
	return c.withDO(c.DO.Limit(limit))
}

func (c certDo) Offset(offset int) *certDo {
	return c.withDO(c.DO.Offset(offset))
}

func (c certDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *certDo {
	return c.withDO(c.DO.Scopes(funcs...))
}

func (c certDo) Unscoped() *certDo {
	return c.withDO(c.DO.Unscoped())
}

func (c certDo) Create(values ...*model.Cert) error {
	if len(values) == 0 {
		return nil
	}
	return c.DO.Create(values)
}

func (c certDo) CreateInBatches(values []*model.Cert, batchSize int) error {
	return c.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 (c certDo) Save(values ...*model.Cert) error {
	if len(values) == 0 {
		return nil
	}
	return c.DO.Save(values)
}

func (c certDo) First() (*model.Cert, error) {
	if result, err := c.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*model.Cert), nil
	}
}

func (c certDo) Take() (*model.Cert, error) {
	if result, err := c.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*model.Cert), nil
	}
}

func (c certDo) Last() (*model.Cert, error) {
	if result, err := c.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*model.Cert), nil
	}
}

func (c certDo) Find() ([]*model.Cert, error) {
	result, err := c.DO.Find()
	return result.([]*model.Cert), err
}

func (c certDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Cert, err error) {
	buf := make([]*model.Cert, 0, batchSize)
	err = c.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 (c certDo) FindInBatches(result *[]*model.Cert, batchSize int, fc func(tx gen.Dao, batch int) error) error {
	return c.DO.FindInBatches(result, batchSize, fc)
}

func (c certDo) Attrs(attrs ...field.AssignExpr) *certDo {
	return c.withDO(c.DO.Attrs(attrs...))
}

func (c certDo) Assign(attrs ...field.AssignExpr) *certDo {
	return c.withDO(c.DO.Assign(attrs...))
}

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

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

func (c certDo) FirstOrInit() (*model.Cert, error) {
	if result, err := c.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*model.Cert), nil
	}
}

func (c certDo) FirstOrCreate() (*model.Cert, error) {
	if result, err := c.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*model.Cert), nil
	}
}

func (c certDo) FindByPage(offset int, limit int) (result []*model.Cert, count int64, err error) {
	result, err = c.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 = c.Offset(-1).Limit(-1).Count()
	return
}

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

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

func (c certDo) Scan(result interface{}) (err error) {
	return c.DO.Scan(result)
}

func (c certDo) Delete(models ...*model.Cert) (result gen.ResultInfo, err error) {
	return c.DO.Delete(models)
}

func (c *certDo) withDO(do gen.Dao) *certDo {
	c.DO = *do.(*gen.DO)
	return c
}
