// Code generated by entc, DO NOT EDIT.

package db

import (
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/dexidp/dex/storage/ent/db/authcode"
)

// AuthCodeCreate is the builder for creating a AuthCode entity.
type AuthCodeCreate struct {
	config
	mutation *AuthCodeMutation
	hooks    []Hook
}

// SetClientID sets the "client_id" field.
func (acc *AuthCodeCreate) SetClientID(s string) *AuthCodeCreate {
	acc.mutation.SetClientID(s)
	return acc
}

// SetScopes sets the "scopes" field.
func (acc *AuthCodeCreate) SetScopes(s []string) *AuthCodeCreate {
	acc.mutation.SetScopes(s)
	return acc
}

// SetNonce sets the "nonce" field.
func (acc *AuthCodeCreate) SetNonce(s string) *AuthCodeCreate {
	acc.mutation.SetNonce(s)
	return acc
}

// SetRedirectURI sets the "redirect_uri" field.
func (acc *AuthCodeCreate) SetRedirectURI(s string) *AuthCodeCreate {
	acc.mutation.SetRedirectURI(s)
	return acc
}

// SetClaimsUserID sets the "claims_user_id" field.
func (acc *AuthCodeCreate) SetClaimsUserID(s string) *AuthCodeCreate {
	acc.mutation.SetClaimsUserID(s)
	return acc
}

// SetClaimsUsername sets the "claims_username" field.
func (acc *AuthCodeCreate) SetClaimsUsername(s string) *AuthCodeCreate {
	acc.mutation.SetClaimsUsername(s)
	return acc
}

// SetClaimsEmail sets the "claims_email" field.
func (acc *AuthCodeCreate) SetClaimsEmail(s string) *AuthCodeCreate {
	acc.mutation.SetClaimsEmail(s)
	return acc
}

// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (acc *AuthCodeCreate) SetClaimsEmailVerified(b bool) *AuthCodeCreate {
	acc.mutation.SetClaimsEmailVerified(b)
	return acc
}

// SetClaimsGroups sets the "claims_groups" field.
func (acc *AuthCodeCreate) SetClaimsGroups(s []string) *AuthCodeCreate {
	acc.mutation.SetClaimsGroups(s)
	return acc
}

// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (acc *AuthCodeCreate) SetClaimsPreferredUsername(s string) *AuthCodeCreate {
	acc.mutation.SetClaimsPreferredUsername(s)
	return acc
}

// SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil.
func (acc *AuthCodeCreate) SetNillableClaimsPreferredUsername(s *string) *AuthCodeCreate {
	if s != nil {
		acc.SetClaimsPreferredUsername(*s)
	}
	return acc
}

// SetConnectorID sets the "connector_id" field.
func (acc *AuthCodeCreate) SetConnectorID(s string) *AuthCodeCreate {
	acc.mutation.SetConnectorID(s)
	return acc
}

// SetConnectorData sets the "connector_data" field.
func (acc *AuthCodeCreate) SetConnectorData(b []byte) *AuthCodeCreate {
	acc.mutation.SetConnectorData(b)
	return acc
}

// SetExpiry sets the "expiry" field.
func (acc *AuthCodeCreate) SetExpiry(t time.Time) *AuthCodeCreate {
	acc.mutation.SetExpiry(t)
	return acc
}

// SetCodeChallenge sets the "code_challenge" field.
func (acc *AuthCodeCreate) SetCodeChallenge(s string) *AuthCodeCreate {
	acc.mutation.SetCodeChallenge(s)
	return acc
}

// SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil.
func (acc *AuthCodeCreate) SetNillableCodeChallenge(s *string) *AuthCodeCreate {
	if s != nil {
		acc.SetCodeChallenge(*s)
	}
	return acc
}

// SetCodeChallengeMethod sets the "code_challenge_method" field.
func (acc *AuthCodeCreate) SetCodeChallengeMethod(s string) *AuthCodeCreate {
	acc.mutation.SetCodeChallengeMethod(s)
	return acc
}

// SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil.
func (acc *AuthCodeCreate) SetNillableCodeChallengeMethod(s *string) *AuthCodeCreate {
	if s != nil {
		acc.SetCodeChallengeMethod(*s)
	}
	return acc
}

// SetID sets the "id" field.
func (acc *AuthCodeCreate) SetID(s string) *AuthCodeCreate {
	acc.mutation.SetID(s)
	return acc
}

// Mutation returns the AuthCodeMutation object of the builder.
func (acc *AuthCodeCreate) Mutation() *AuthCodeMutation {
	return acc.mutation
}

// Save creates the AuthCode in the database.
func (acc *AuthCodeCreate) Save(ctx context.Context) (*AuthCode, error) {
	var (
		err  error
		node *AuthCode
	)
	acc.defaults()
	if len(acc.hooks) == 0 {
		if err = acc.check(); err != nil {
			return nil, err
		}
		node, err = acc.sqlSave(ctx)
	} else {
		var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
			mutation, ok := m.(*AuthCodeMutation)
			if !ok {
				return nil, fmt.Errorf("unexpected mutation type %T", m)
			}
			if err = acc.check(); err != nil {
				return nil, err
			}
			acc.mutation = mutation
			if node, err = acc.sqlSave(ctx); err != nil {
				return nil, err
			}
			mutation.id = &node.ID
			mutation.done = true
			return node, err
		})
		for i := len(acc.hooks) - 1; i >= 0; i-- {
			if acc.hooks[i] == nil {
				return nil, fmt.Errorf("db: uninitialized hook (forgotten import db/runtime?)")
			}
			mut = acc.hooks[i](mut)
		}
		if _, err := mut.Mutate(ctx, acc.mutation); err != nil {
			return nil, err
		}
	}
	return node, err
}

// SaveX calls Save and panics if Save returns an error.
func (acc *AuthCodeCreate) SaveX(ctx context.Context) *AuthCode {
	v, err := acc.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

// Exec executes the query.
func (acc *AuthCodeCreate) Exec(ctx context.Context) error {
	_, err := acc.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (acc *AuthCodeCreate) ExecX(ctx context.Context) {
	if err := acc.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (acc *AuthCodeCreate) defaults() {
	if _, ok := acc.mutation.ClaimsPreferredUsername(); !ok {
		v := authcode.DefaultClaimsPreferredUsername
		acc.mutation.SetClaimsPreferredUsername(v)
	}
	if _, ok := acc.mutation.CodeChallenge(); !ok {
		v := authcode.DefaultCodeChallenge
		acc.mutation.SetCodeChallenge(v)
	}
	if _, ok := acc.mutation.CodeChallengeMethod(); !ok {
		v := authcode.DefaultCodeChallengeMethod
		acc.mutation.SetCodeChallengeMethod(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (acc *AuthCodeCreate) check() error {
	if _, ok := acc.mutation.ClientID(); !ok {
		return &ValidationError{Name: "client_id", err: errors.New(`db: missing required field "client_id"`)}
	}
	if v, ok := acc.mutation.ClientID(); ok {
		if err := authcode.ClientIDValidator(v); err != nil {
			return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "client_id": %w`, err)}
		}
	}
	if _, ok := acc.mutation.Nonce(); !ok {
		return &ValidationError{Name: "nonce", err: errors.New(`db: missing required field "nonce"`)}
	}
	if v, ok := acc.mutation.Nonce(); ok {
		if err := authcode.NonceValidator(v); err != nil {
			return &ValidationError{Name: "nonce", err: fmt.Errorf(`db: validator failed for field "nonce": %w`, err)}
		}
	}
	if _, ok := acc.mutation.RedirectURI(); !ok {
		return &ValidationError{Name: "redirect_uri", err: errors.New(`db: missing required field "redirect_uri"`)}
	}
	if v, ok := acc.mutation.RedirectURI(); ok {
		if err := authcode.RedirectURIValidator(v); err != nil {
			return &ValidationError{Name: "redirect_uri", err: fmt.Errorf(`db: validator failed for field "redirect_uri": %w`, err)}
		}
	}
	if _, ok := acc.mutation.ClaimsUserID(); !ok {
		return &ValidationError{Name: "claims_user_id", err: errors.New(`db: missing required field "claims_user_id"`)}
	}
	if v, ok := acc.mutation.ClaimsUserID(); ok {
		if err := authcode.ClaimsUserIDValidator(v); err != nil {
			return &ValidationError{Name: "claims_user_id", err: fmt.Errorf(`db: validator failed for field "claims_user_id": %w`, err)}
		}
	}
	if _, ok := acc.mutation.ClaimsUsername(); !ok {
		return &ValidationError{Name: "claims_username", err: errors.New(`db: missing required field "claims_username"`)}
	}
	if v, ok := acc.mutation.ClaimsUsername(); ok {
		if err := authcode.ClaimsUsernameValidator(v); err != nil {
			return &ValidationError{Name: "claims_username", err: fmt.Errorf(`db: validator failed for field "claims_username": %w`, err)}
		}
	}
	if _, ok := acc.mutation.ClaimsEmail(); !ok {
		return &ValidationError{Name: "claims_email", err: errors.New(`db: missing required field "claims_email"`)}
	}
	if v, ok := acc.mutation.ClaimsEmail(); ok {
		if err := authcode.ClaimsEmailValidator(v); err != nil {
			return &ValidationError{Name: "claims_email", err: fmt.Errorf(`db: validator failed for field "claims_email": %w`, err)}
		}
	}
	if _, ok := acc.mutation.ClaimsEmailVerified(); !ok {
		return &ValidationError{Name: "claims_email_verified", err: errors.New(`db: missing required field "claims_email_verified"`)}
	}
	if _, ok := acc.mutation.ClaimsPreferredUsername(); !ok {
		return &ValidationError{Name: "claims_preferred_username", err: errors.New(`db: missing required field "claims_preferred_username"`)}
	}
	if _, ok := acc.mutation.ConnectorID(); !ok {
		return &ValidationError{Name: "connector_id", err: errors.New(`db: missing required field "connector_id"`)}
	}
	if v, ok := acc.mutation.ConnectorID(); ok {
		if err := authcode.ConnectorIDValidator(v); err != nil {
			return &ValidationError{Name: "connector_id", err: fmt.Errorf(`db: validator failed for field "connector_id": %w`, err)}
		}
	}
	if _, ok := acc.mutation.Expiry(); !ok {
		return &ValidationError{Name: "expiry", err: errors.New(`db: missing required field "expiry"`)}
	}
	if _, ok := acc.mutation.CodeChallenge(); !ok {
		return &ValidationError{Name: "code_challenge", err: errors.New(`db: missing required field "code_challenge"`)}
	}
	if _, ok := acc.mutation.CodeChallengeMethod(); !ok {
		return &ValidationError{Name: "code_challenge_method", err: errors.New(`db: missing required field "code_challenge_method"`)}
	}
	if v, ok := acc.mutation.ID(); ok {
		if err := authcode.IDValidator(v); err != nil {
			return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "id": %w`, err)}
		}
	}
	return nil
}

func (acc *AuthCodeCreate) sqlSave(ctx context.Context) (*AuthCode, error) {
	_node, _spec := acc.createSpec()
	if err := sqlgraph.CreateNode(ctx, acc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{err.Error(), err}
		}
		return nil, err
	}
	return _node, nil
}

func (acc *AuthCodeCreate) createSpec() (*AuthCode, *sqlgraph.CreateSpec) {
	var (
		_node = &AuthCode{config: acc.config}
		_spec = &sqlgraph.CreateSpec{
			Table: authcode.Table,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeString,
				Column: authcode.FieldID,
			},
		}
	)
	if id, ok := acc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = id
	}
	if value, ok := acc.mutation.ClientID(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldClientID,
		})
		_node.ClientID = value
	}
	if value, ok := acc.mutation.Scopes(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeJSON,
			Value:  value,
			Column: authcode.FieldScopes,
		})
		_node.Scopes = value
	}
	if value, ok := acc.mutation.Nonce(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldNonce,
		})
		_node.Nonce = value
	}
	if value, ok := acc.mutation.RedirectURI(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldRedirectURI,
		})
		_node.RedirectURI = value
	}
	if value, ok := acc.mutation.ClaimsUserID(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldClaimsUserID,
		})
		_node.ClaimsUserID = value
	}
	if value, ok := acc.mutation.ClaimsUsername(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldClaimsUsername,
		})
		_node.ClaimsUsername = value
	}
	if value, ok := acc.mutation.ClaimsEmail(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldClaimsEmail,
		})
		_node.ClaimsEmail = value
	}
	if value, ok := acc.mutation.ClaimsEmailVerified(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeBool,
			Value:  value,
			Column: authcode.FieldClaimsEmailVerified,
		})
		_node.ClaimsEmailVerified = value
	}
	if value, ok := acc.mutation.ClaimsGroups(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeJSON,
			Value:  value,
			Column: authcode.FieldClaimsGroups,
		})
		_node.ClaimsGroups = value
	}
	if value, ok := acc.mutation.ClaimsPreferredUsername(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldClaimsPreferredUsername,
		})
		_node.ClaimsPreferredUsername = value
	}
	if value, ok := acc.mutation.ConnectorID(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldConnectorID,
		})
		_node.ConnectorID = value
	}
	if value, ok := acc.mutation.ConnectorData(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeBytes,
			Value:  value,
			Column: authcode.FieldConnectorData,
		})
		_node.ConnectorData = &value
	}
	if value, ok := acc.mutation.Expiry(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: authcode.FieldExpiry,
		})
		_node.Expiry = value
	}
	if value, ok := acc.mutation.CodeChallenge(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldCodeChallenge,
		})
		_node.CodeChallenge = value
	}
	if value, ok := acc.mutation.CodeChallengeMethod(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: authcode.FieldCodeChallengeMethod,
		})
		_node.CodeChallengeMethod = value
	}
	return _node, _spec
}

// AuthCodeCreateBulk is the builder for creating many AuthCode entities in bulk.
type AuthCodeCreateBulk struct {
	config
	builders []*AuthCodeCreate
}

// Save creates the AuthCode entities in the database.
func (accb *AuthCodeCreateBulk) Save(ctx context.Context) ([]*AuthCode, error) {
	specs := make([]*sqlgraph.CreateSpec, len(accb.builders))
	nodes := make([]*AuthCode, len(accb.builders))
	mutators := make([]Mutator, len(accb.builders))
	for i := range accb.builders {
		func(i int, root context.Context) {
			builder := accb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*AuthCodeMutation)
				if !ok {
					return nil, fmt.Errorf("unexpected mutation type %T", m)
				}
				if err := builder.check(); err != nil {
					return nil, err
				}
				builder.mutation = mutation
				nodes[i], specs[i] = builder.createSpec()
				var err error
				if i < len(mutators)-1 {
					_, err = mutators[i+1].Mutate(root, accb.builders[i+1].mutation)
				} else {
					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, accb.driver, spec); err != nil {
						if sqlgraph.IsConstraintError(err) {
							err = &ConstraintError{err.Error(), err}
						}
					}
				}
				if err != nil {
					return nil, err
				}
				mutation.id = &nodes[i].ID
				mutation.done = true
				return nodes[i], nil
			})
			for i := len(builder.hooks) - 1; i >= 0; i-- {
				mut = builder.hooks[i](mut)
			}
			mutators[i] = mut
		}(i, ctx)
	}
	if len(mutators) > 0 {
		if _, err := mutators[0].Mutate(ctx, accb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

// SaveX is like Save, but panics if an error occurs.
func (accb *AuthCodeCreateBulk) SaveX(ctx context.Context) []*AuthCode {
	v, err := accb.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

// Exec executes the query.
func (accb *AuthCodeCreateBulk) Exec(ctx context.Context) error {
	_, err := accb.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (accb *AuthCodeCreateBulk) ExecX(ctx context.Context) {
	if err := accb.Exec(ctx); err != nil {
		panic(err)
	}
}