// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/casbackend"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/organization"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun"
	"github.com/google/uuid"
)

// CASBackendCreate is the builder for creating a CASBackend entity.
type CASBackendCreate struct {
	config
	mutation *CASBackendMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetLocation sets the "location" field.
func (cbc *CASBackendCreate) SetLocation(s string) *CASBackendCreate {
	cbc.mutation.SetLocation(s)
	return cbc
}

// SetName sets the "name" field.
func (cbc *CASBackendCreate) SetName(s string) *CASBackendCreate {
	cbc.mutation.SetName(s)
	return cbc
}

// SetProvider sets the "provider" field.
func (cbc *CASBackendCreate) SetProvider(bbp biz.CASBackendProvider) *CASBackendCreate {
	cbc.mutation.SetProvider(bbp)
	return cbc
}

// SetDescription sets the "description" field.
func (cbc *CASBackendCreate) SetDescription(s string) *CASBackendCreate {
	cbc.mutation.SetDescription(s)
	return cbc
}

// SetNillableDescription sets the "description" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableDescription(s *string) *CASBackendCreate {
	if s != nil {
		cbc.SetDescription(*s)
	}
	return cbc
}

// SetSecretName sets the "secret_name" field.
func (cbc *CASBackendCreate) SetSecretName(s string) *CASBackendCreate {
	cbc.mutation.SetSecretName(s)
	return cbc
}

// SetCreatedAt sets the "created_at" field.
func (cbc *CASBackendCreate) SetCreatedAt(t time.Time) *CASBackendCreate {
	cbc.mutation.SetCreatedAt(t)
	return cbc
}

// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableCreatedAt(t *time.Time) *CASBackendCreate {
	if t != nil {
		cbc.SetCreatedAt(*t)
	}
	return cbc
}

// SetValidationStatus sets the "validation_status" field.
func (cbc *CASBackendCreate) SetValidationStatus(bbvs biz.CASBackendValidationStatus) *CASBackendCreate {
	cbc.mutation.SetValidationStatus(bbvs)
	return cbc
}

// SetNillableValidationStatus sets the "validation_status" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableValidationStatus(bbvs *biz.CASBackendValidationStatus) *CASBackendCreate {
	if bbvs != nil {
		cbc.SetValidationStatus(*bbvs)
	}
	return cbc
}

// SetValidationError sets the "validation_error" field.
func (cbc *CASBackendCreate) SetValidationError(s string) *CASBackendCreate {
	cbc.mutation.SetValidationError(s)
	return cbc
}

// SetNillableValidationError sets the "validation_error" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableValidationError(s *string) *CASBackendCreate {
	if s != nil {
		cbc.SetValidationError(*s)
	}
	return cbc
}

// SetValidatedAt sets the "validated_at" field.
func (cbc *CASBackendCreate) SetValidatedAt(t time.Time) *CASBackendCreate {
	cbc.mutation.SetValidatedAt(t)
	return cbc
}

// SetNillableValidatedAt sets the "validated_at" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableValidatedAt(t *time.Time) *CASBackendCreate {
	if t != nil {
		cbc.SetValidatedAt(*t)
	}
	return cbc
}

// SetDefault sets the "default" field.
func (cbc *CASBackendCreate) SetDefault(b bool) *CASBackendCreate {
	cbc.mutation.SetDefault(b)
	return cbc
}

// SetNillableDefault sets the "default" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableDefault(b *bool) *CASBackendCreate {
	if b != nil {
		cbc.SetDefault(*b)
	}
	return cbc
}

// SetDeletedAt sets the "deleted_at" field.
func (cbc *CASBackendCreate) SetDeletedAt(t time.Time) *CASBackendCreate {
	cbc.mutation.SetDeletedAt(t)
	return cbc
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableDeletedAt(t *time.Time) *CASBackendCreate {
	if t != nil {
		cbc.SetDeletedAt(*t)
	}
	return cbc
}

// SetFallback sets the "fallback" field.
func (cbc *CASBackendCreate) SetFallback(b bool) *CASBackendCreate {
	cbc.mutation.SetFallback(b)
	return cbc
}

// SetNillableFallback sets the "fallback" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableFallback(b *bool) *CASBackendCreate {
	if b != nil {
		cbc.SetFallback(*b)
	}
	return cbc
}

// SetMaxBlobSizeBytes sets the "max_blob_size_bytes" field.
func (cbc *CASBackendCreate) SetMaxBlobSizeBytes(i int64) *CASBackendCreate {
	cbc.mutation.SetMaxBlobSizeBytes(i)
	return cbc
}

// SetID sets the "id" field.
func (cbc *CASBackendCreate) SetID(u uuid.UUID) *CASBackendCreate {
	cbc.mutation.SetID(u)
	return cbc
}

// SetNillableID sets the "id" field if the given value is not nil.
func (cbc *CASBackendCreate) SetNillableID(u *uuid.UUID) *CASBackendCreate {
	if u != nil {
		cbc.SetID(*u)
	}
	return cbc
}

// SetOrganizationID sets the "organization" edge to the Organization entity by ID.
func (cbc *CASBackendCreate) SetOrganizationID(id uuid.UUID) *CASBackendCreate {
	cbc.mutation.SetOrganizationID(id)
	return cbc
}

// SetOrganization sets the "organization" edge to the Organization entity.
func (cbc *CASBackendCreate) SetOrganization(o *Organization) *CASBackendCreate {
	return cbc.SetOrganizationID(o.ID)
}

// AddWorkflowRunIDs adds the "workflow_run" edge to the WorkflowRun entity by IDs.
func (cbc *CASBackendCreate) AddWorkflowRunIDs(ids ...uuid.UUID) *CASBackendCreate {
	cbc.mutation.AddWorkflowRunIDs(ids...)
	return cbc
}

// AddWorkflowRun adds the "workflow_run" edges to the WorkflowRun entity.
func (cbc *CASBackendCreate) AddWorkflowRun(w ...*WorkflowRun) *CASBackendCreate {
	ids := make([]uuid.UUID, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return cbc.AddWorkflowRunIDs(ids...)
}

// Mutation returns the CASBackendMutation object of the builder.
func (cbc *CASBackendCreate) Mutation() *CASBackendMutation {
	return cbc.mutation
}

// Save creates the CASBackend in the database.
func (cbc *CASBackendCreate) Save(ctx context.Context) (*CASBackend, error) {
	cbc.defaults()
	return withHooks(ctx, cbc.sqlSave, cbc.mutation, cbc.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (cbc *CASBackendCreate) defaults() {
	if _, ok := cbc.mutation.CreatedAt(); !ok {
		v := casbackend.DefaultCreatedAt()
		cbc.mutation.SetCreatedAt(v)
	}
	if _, ok := cbc.mutation.ValidationStatus(); !ok {
		v := casbackend.DefaultValidationStatus
		cbc.mutation.SetValidationStatus(v)
	}
	if _, ok := cbc.mutation.ValidatedAt(); !ok {
		v := casbackend.DefaultValidatedAt()
		cbc.mutation.SetValidatedAt(v)
	}
	if _, ok := cbc.mutation.Default(); !ok {
		v := casbackend.DefaultDefault
		cbc.mutation.SetDefault(v)
	}
	if _, ok := cbc.mutation.Fallback(); !ok {
		v := casbackend.DefaultFallback
		cbc.mutation.SetFallback(v)
	}
	if _, ok := cbc.mutation.ID(); !ok {
		v := casbackend.DefaultID()
		cbc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (cbc *CASBackendCreate) check() error {
	if _, ok := cbc.mutation.Location(); !ok {
		return &ValidationError{Name: "location", err: errors.New(`ent: missing required field "CASBackend.location"`)}
	}
	if _, ok := cbc.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "CASBackend.name"`)}
	}
	if _, ok := cbc.mutation.Provider(); !ok {
		return &ValidationError{Name: "provider", err: errors.New(`ent: missing required field "CASBackend.provider"`)}
	}
	if v, ok := cbc.mutation.Provider(); ok {
		if err := casbackend.ProviderValidator(v); err != nil {
			return &ValidationError{Name: "provider", err: fmt.Errorf(`ent: validator failed for field "CASBackend.provider": %w`, err)}
		}
	}
	if _, ok := cbc.mutation.SecretName(); !ok {
		return &ValidationError{Name: "secret_name", err: errors.New(`ent: missing required field "CASBackend.secret_name"`)}
	}
	if _, ok := cbc.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "CASBackend.created_at"`)}
	}
	if _, ok := cbc.mutation.ValidationStatus(); !ok {
		return &ValidationError{Name: "validation_status", err: errors.New(`ent: missing required field "CASBackend.validation_status"`)}
	}
	if v, ok := cbc.mutation.ValidationStatus(); ok {
		if err := casbackend.ValidationStatusValidator(v); err != nil {
			return &ValidationError{Name: "validation_status", err: fmt.Errorf(`ent: validator failed for field "CASBackend.validation_status": %w`, err)}
		}
	}
	if _, ok := cbc.mutation.ValidatedAt(); !ok {
		return &ValidationError{Name: "validated_at", err: errors.New(`ent: missing required field "CASBackend.validated_at"`)}
	}
	if _, ok := cbc.mutation.Default(); !ok {
		return &ValidationError{Name: "default", err: errors.New(`ent: missing required field "CASBackend.default"`)}
	}
	if _, ok := cbc.mutation.Fallback(); !ok {
		return &ValidationError{Name: "fallback", err: errors.New(`ent: missing required field "CASBackend.fallback"`)}
	}
	if _, ok := cbc.mutation.MaxBlobSizeBytes(); !ok {
		return &ValidationError{Name: "max_blob_size_bytes", err: errors.New(`ent: missing required field "CASBackend.max_blob_size_bytes"`)}
	}
	if len(cbc.mutation.OrganizationIDs()) == 0 {
		return &ValidationError{Name: "organization", err: errors.New(`ent: missing required edge "CASBackend.organization"`)}
	}
	return nil
}

func (cbc *CASBackendCreate) sqlSave(ctx context.Context) (*CASBackend, error) {
	if err := cbc.check(); err != nil {
		return nil, err
	}
	_node, _spec := cbc.createSpec()
	if err := sqlgraph.CreateNode(ctx, cbc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	if _spec.ID.Value != nil {
		if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
			_node.ID = *id
		} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
			return nil, err
		}
	}
	cbc.mutation.id = &_node.ID
	cbc.mutation.done = true
	return _node, nil
}

func (cbc *CASBackendCreate) createSpec() (*CASBackend, *sqlgraph.CreateSpec) {
	var (
		_node = &CASBackend{config: cbc.config}
		_spec = sqlgraph.NewCreateSpec(casbackend.Table, sqlgraph.NewFieldSpec(casbackend.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = cbc.conflict
	if id, ok := cbc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := cbc.mutation.Location(); ok {
		_spec.SetField(casbackend.FieldLocation, field.TypeString, value)
		_node.Location = value
	}
	if value, ok := cbc.mutation.Name(); ok {
		_spec.SetField(casbackend.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := cbc.mutation.Provider(); ok {
		_spec.SetField(casbackend.FieldProvider, field.TypeEnum, value)
		_node.Provider = value
	}
	if value, ok := cbc.mutation.Description(); ok {
		_spec.SetField(casbackend.FieldDescription, field.TypeString, value)
		_node.Description = value
	}
	if value, ok := cbc.mutation.SecretName(); ok {
		_spec.SetField(casbackend.FieldSecretName, field.TypeString, value)
		_node.SecretName = value
	}
	if value, ok := cbc.mutation.CreatedAt(); ok {
		_spec.SetField(casbackend.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := cbc.mutation.ValidationStatus(); ok {
		_spec.SetField(casbackend.FieldValidationStatus, field.TypeEnum, value)
		_node.ValidationStatus = value
	}
	if value, ok := cbc.mutation.ValidationError(); ok {
		_spec.SetField(casbackend.FieldValidationError, field.TypeString, value)
		_node.ValidationError = value
	}
	if value, ok := cbc.mutation.ValidatedAt(); ok {
		_spec.SetField(casbackend.FieldValidatedAt, field.TypeTime, value)
		_node.ValidatedAt = value
	}
	if value, ok := cbc.mutation.Default(); ok {
		_spec.SetField(casbackend.FieldDefault, field.TypeBool, value)
		_node.Default = value
	}
	if value, ok := cbc.mutation.DeletedAt(); ok {
		_spec.SetField(casbackend.FieldDeletedAt, field.TypeTime, value)
		_node.DeletedAt = value
	}
	if value, ok := cbc.mutation.Fallback(); ok {
		_spec.SetField(casbackend.FieldFallback, field.TypeBool, value)
		_node.Fallback = value
	}
	if value, ok := cbc.mutation.MaxBlobSizeBytes(); ok {
		_spec.SetField(casbackend.FieldMaxBlobSizeBytes, field.TypeInt64, value)
		_node.MaxBlobSizeBytes = value
	}
	if nodes := cbc.mutation.OrganizationIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   casbackend.OrganizationTable,
			Columns: []string{casbackend.OrganizationColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(organization.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.organization_cas_backends = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := cbc.mutation.WorkflowRunIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   casbackend.WorkflowRunTable,
			Columns: casbackend.WorkflowRunPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(workflowrun.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.CASBackend.Create().
//		SetLocation(v).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.CASBackendUpsert) {
//			SetLocation(v+v).
//		}).
//		Exec(ctx)
func (cbc *CASBackendCreate) OnConflict(opts ...sql.ConflictOption) *CASBackendUpsertOne {
	cbc.conflict = opts
	return &CASBackendUpsertOne{
		create: cbc,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.CASBackend.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (cbc *CASBackendCreate) OnConflictColumns(columns ...string) *CASBackendUpsertOne {
	cbc.conflict = append(cbc.conflict, sql.ConflictColumns(columns...))
	return &CASBackendUpsertOne{
		create: cbc,
	}
}

type (
	// CASBackendUpsertOne is the builder for "upsert"-ing
	//  one CASBackend node.
	CASBackendUpsertOne struct {
		create *CASBackendCreate
	}

	// CASBackendUpsert is the "OnConflict" setter.
	CASBackendUpsert struct {
		*sql.UpdateSet
	}
)

// SetDescription sets the "description" field.
func (u *CASBackendUpsert) SetDescription(v string) *CASBackendUpsert {
	u.Set(casbackend.FieldDescription, v)
	return u
}

// UpdateDescription sets the "description" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateDescription() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldDescription)
	return u
}

// ClearDescription clears the value of the "description" field.
func (u *CASBackendUpsert) ClearDescription() *CASBackendUpsert {
	u.SetNull(casbackend.FieldDescription)
	return u
}

// SetSecretName sets the "secret_name" field.
func (u *CASBackendUpsert) SetSecretName(v string) *CASBackendUpsert {
	u.Set(casbackend.FieldSecretName, v)
	return u
}

// UpdateSecretName sets the "secret_name" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateSecretName() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldSecretName)
	return u
}

// SetValidationStatus sets the "validation_status" field.
func (u *CASBackendUpsert) SetValidationStatus(v biz.CASBackendValidationStatus) *CASBackendUpsert {
	u.Set(casbackend.FieldValidationStatus, v)
	return u
}

// UpdateValidationStatus sets the "validation_status" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateValidationStatus() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldValidationStatus)
	return u
}

// SetValidationError sets the "validation_error" field.
func (u *CASBackendUpsert) SetValidationError(v string) *CASBackendUpsert {
	u.Set(casbackend.FieldValidationError, v)
	return u
}

// UpdateValidationError sets the "validation_error" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateValidationError() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldValidationError)
	return u
}

// ClearValidationError clears the value of the "validation_error" field.
func (u *CASBackendUpsert) ClearValidationError() *CASBackendUpsert {
	u.SetNull(casbackend.FieldValidationError)
	return u
}

// SetValidatedAt sets the "validated_at" field.
func (u *CASBackendUpsert) SetValidatedAt(v time.Time) *CASBackendUpsert {
	u.Set(casbackend.FieldValidatedAt, v)
	return u
}

// UpdateValidatedAt sets the "validated_at" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateValidatedAt() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldValidatedAt)
	return u
}

// SetDefault sets the "default" field.
func (u *CASBackendUpsert) SetDefault(v bool) *CASBackendUpsert {
	u.Set(casbackend.FieldDefault, v)
	return u
}

// UpdateDefault sets the "default" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateDefault() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldDefault)
	return u
}

// SetDeletedAt sets the "deleted_at" field.
func (u *CASBackendUpsert) SetDeletedAt(v time.Time) *CASBackendUpsert {
	u.Set(casbackend.FieldDeletedAt, v)
	return u
}

// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateDeletedAt() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldDeletedAt)
	return u
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *CASBackendUpsert) ClearDeletedAt() *CASBackendUpsert {
	u.SetNull(casbackend.FieldDeletedAt)
	return u
}

// SetMaxBlobSizeBytes sets the "max_blob_size_bytes" field.
func (u *CASBackendUpsert) SetMaxBlobSizeBytes(v int64) *CASBackendUpsert {
	u.Set(casbackend.FieldMaxBlobSizeBytes, v)
	return u
}

// UpdateMaxBlobSizeBytes sets the "max_blob_size_bytes" field to the value that was provided on create.
func (u *CASBackendUpsert) UpdateMaxBlobSizeBytes() *CASBackendUpsert {
	u.SetExcluded(casbackend.FieldMaxBlobSizeBytes)
	return u
}

// AddMaxBlobSizeBytes adds v to the "max_blob_size_bytes" field.
func (u *CASBackendUpsert) AddMaxBlobSizeBytes(v int64) *CASBackendUpsert {
	u.Add(casbackend.FieldMaxBlobSizeBytes, v)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
// Using this option is equivalent to using:
//
//	client.CASBackend.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(casbackend.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *CASBackendUpsertOne) UpdateNewValues() *CASBackendUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		if _, exists := u.create.mutation.ID(); exists {
			s.SetIgnore(casbackend.FieldID)
		}
		if _, exists := u.create.mutation.Location(); exists {
			s.SetIgnore(casbackend.FieldLocation)
		}
		if _, exists := u.create.mutation.Name(); exists {
			s.SetIgnore(casbackend.FieldName)
		}
		if _, exists := u.create.mutation.Provider(); exists {
			s.SetIgnore(casbackend.FieldProvider)
		}
		if _, exists := u.create.mutation.CreatedAt(); exists {
			s.SetIgnore(casbackend.FieldCreatedAt)
		}
		if _, exists := u.create.mutation.Fallback(); exists {
			s.SetIgnore(casbackend.FieldFallback)
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.CASBackend.Create().
//	    OnConflict(sql.ResolveWithIgnore()).
//	    Exec(ctx)
func (u *CASBackendUpsertOne) Ignore() *CASBackendUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *CASBackendUpsertOne) DoNothing() *CASBackendUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the CASBackendCreate.OnConflict
// documentation for more info.
func (u *CASBackendUpsertOne) Update(set func(*CASBackendUpsert)) *CASBackendUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&CASBackendUpsert{UpdateSet: update})
	}))
	return u
}

// SetDescription sets the "description" field.
func (u *CASBackendUpsertOne) SetDescription(v string) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetDescription(v)
	})
}

// UpdateDescription sets the "description" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateDescription() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateDescription()
	})
}

// ClearDescription clears the value of the "description" field.
func (u *CASBackendUpsertOne) ClearDescription() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.ClearDescription()
	})
}

// SetSecretName sets the "secret_name" field.
func (u *CASBackendUpsertOne) SetSecretName(v string) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetSecretName(v)
	})
}

// UpdateSecretName sets the "secret_name" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateSecretName() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateSecretName()
	})
}

// SetValidationStatus sets the "validation_status" field.
func (u *CASBackendUpsertOne) SetValidationStatus(v biz.CASBackendValidationStatus) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetValidationStatus(v)
	})
}

// UpdateValidationStatus sets the "validation_status" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateValidationStatus() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateValidationStatus()
	})
}

// SetValidationError sets the "validation_error" field.
func (u *CASBackendUpsertOne) SetValidationError(v string) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetValidationError(v)
	})
}

// UpdateValidationError sets the "validation_error" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateValidationError() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateValidationError()
	})
}

// ClearValidationError clears the value of the "validation_error" field.
func (u *CASBackendUpsertOne) ClearValidationError() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.ClearValidationError()
	})
}

// SetValidatedAt sets the "validated_at" field.
func (u *CASBackendUpsertOne) SetValidatedAt(v time.Time) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetValidatedAt(v)
	})
}

// UpdateValidatedAt sets the "validated_at" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateValidatedAt() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateValidatedAt()
	})
}

// SetDefault sets the "default" field.
func (u *CASBackendUpsertOne) SetDefault(v bool) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetDefault(v)
	})
}

// UpdateDefault sets the "default" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateDefault() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateDefault()
	})
}

// SetDeletedAt sets the "deleted_at" field.
func (u *CASBackendUpsertOne) SetDeletedAt(v time.Time) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetDeletedAt(v)
	})
}

// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateDeletedAt() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateDeletedAt()
	})
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *CASBackendUpsertOne) ClearDeletedAt() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.ClearDeletedAt()
	})
}

// SetMaxBlobSizeBytes sets the "max_blob_size_bytes" field.
func (u *CASBackendUpsertOne) SetMaxBlobSizeBytes(v int64) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetMaxBlobSizeBytes(v)
	})
}

// AddMaxBlobSizeBytes adds v to the "max_blob_size_bytes" field.
func (u *CASBackendUpsertOne) AddMaxBlobSizeBytes(v int64) *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.AddMaxBlobSizeBytes(v)
	})
}

// UpdateMaxBlobSizeBytes sets the "max_blob_size_bytes" field to the value that was provided on create.
func (u *CASBackendUpsertOne) UpdateMaxBlobSizeBytes() *CASBackendUpsertOne {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateMaxBlobSizeBytes()
	})
}

// Exec executes the query.
func (u *CASBackendUpsertOne) Exec(ctx context.Context) error {
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for CASBackendCreate.OnConflict")
	}
	return u.create.Exec(ctx)
}

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

// Exec executes the UPSERT query and returns the inserted/updated ID.
func (u *CASBackendUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
	if u.create.driver.Dialect() == dialect.MySQL {
		// In case of "ON CONFLICT", there is no way to get back non-numeric ID
		// fields from the database since MySQL does not support the RETURNING clause.
		return id, errors.New("ent: CASBackendUpsertOne.ID is not supported by MySQL driver. Use CASBackendUpsertOne.Exec instead")
	}
	node, err := u.create.Save(ctx)
	if err != nil {
		return id, err
	}
	return node.ID, nil
}

// IDX is like ID, but panics if an error occurs.
func (u *CASBackendUpsertOne) IDX(ctx context.Context) uuid.UUID {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// CASBackendCreateBulk is the builder for creating many CASBackend entities in bulk.
type CASBackendCreateBulk struct {
	config
	err      error
	builders []*CASBackendCreate
	conflict []sql.ConflictOption
}

// Save creates the CASBackend entities in the database.
func (cbcb *CASBackendCreateBulk) Save(ctx context.Context) ([]*CASBackend, error) {
	if cbcb.err != nil {
		return nil, cbcb.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(cbcb.builders))
	nodes := make([]*CASBackend, len(cbcb.builders))
	mutators := make([]Mutator, len(cbcb.builders))
	for i := range cbcb.builders {
		func(i int, root context.Context) {
			builder := cbcb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*CASBackendMutation)
				if !ok {
					return nil, fmt.Errorf("unexpected mutation type %T", m)
				}
				if err := builder.check(); err != nil {
					return nil, err
				}
				builder.mutation = mutation
				var err error
				nodes[i], specs[i] = builder.createSpec()
				if i < len(mutators)-1 {
					_, err = mutators[i+1].Mutate(root, cbcb.builders[i+1].mutation)
				} else {
					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
					spec.OnConflict = cbcb.conflict
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, cbcb.driver, spec); err != nil {
						if sqlgraph.IsConstraintError(err) {
							err = &ConstraintError{msg: err.Error(), wrap: 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, cbcb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.CASBackend.CreateBulk(builders...).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.CASBackendUpsert) {
//			SetLocation(v+v).
//		}).
//		Exec(ctx)
func (cbcb *CASBackendCreateBulk) OnConflict(opts ...sql.ConflictOption) *CASBackendUpsertBulk {
	cbcb.conflict = opts
	return &CASBackendUpsertBulk{
		create: cbcb,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.CASBackend.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (cbcb *CASBackendCreateBulk) OnConflictColumns(columns ...string) *CASBackendUpsertBulk {
	cbcb.conflict = append(cbcb.conflict, sql.ConflictColumns(columns...))
	return &CASBackendUpsertBulk{
		create: cbcb,
	}
}

// CASBackendUpsertBulk is the builder for "upsert"-ing
// a bulk of CASBackend nodes.
type CASBackendUpsertBulk struct {
	create *CASBackendCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.CASBackend.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(casbackend.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *CASBackendUpsertBulk) UpdateNewValues() *CASBackendUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		for _, b := range u.create.builders {
			if _, exists := b.mutation.ID(); exists {
				s.SetIgnore(casbackend.FieldID)
			}
			if _, exists := b.mutation.Location(); exists {
				s.SetIgnore(casbackend.FieldLocation)
			}
			if _, exists := b.mutation.Name(); exists {
				s.SetIgnore(casbackend.FieldName)
			}
			if _, exists := b.mutation.Provider(); exists {
				s.SetIgnore(casbackend.FieldProvider)
			}
			if _, exists := b.mutation.CreatedAt(); exists {
				s.SetIgnore(casbackend.FieldCreatedAt)
			}
			if _, exists := b.mutation.Fallback(); exists {
				s.SetIgnore(casbackend.FieldFallback)
			}
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.CASBackend.Create().
//		OnConflict(sql.ResolveWithIgnore()).
//		Exec(ctx)
func (u *CASBackendUpsertBulk) Ignore() *CASBackendUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *CASBackendUpsertBulk) DoNothing() *CASBackendUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the CASBackendCreateBulk.OnConflict
// documentation for more info.
func (u *CASBackendUpsertBulk) Update(set func(*CASBackendUpsert)) *CASBackendUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&CASBackendUpsert{UpdateSet: update})
	}))
	return u
}

// SetDescription sets the "description" field.
func (u *CASBackendUpsertBulk) SetDescription(v string) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetDescription(v)
	})
}

// UpdateDescription sets the "description" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateDescription() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateDescription()
	})
}

// ClearDescription clears the value of the "description" field.
func (u *CASBackendUpsertBulk) ClearDescription() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.ClearDescription()
	})
}

// SetSecretName sets the "secret_name" field.
func (u *CASBackendUpsertBulk) SetSecretName(v string) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetSecretName(v)
	})
}

// UpdateSecretName sets the "secret_name" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateSecretName() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateSecretName()
	})
}

// SetValidationStatus sets the "validation_status" field.
func (u *CASBackendUpsertBulk) SetValidationStatus(v biz.CASBackendValidationStatus) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetValidationStatus(v)
	})
}

// UpdateValidationStatus sets the "validation_status" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateValidationStatus() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateValidationStatus()
	})
}

// SetValidationError sets the "validation_error" field.
func (u *CASBackendUpsertBulk) SetValidationError(v string) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetValidationError(v)
	})
}

// UpdateValidationError sets the "validation_error" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateValidationError() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateValidationError()
	})
}

// ClearValidationError clears the value of the "validation_error" field.
func (u *CASBackendUpsertBulk) ClearValidationError() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.ClearValidationError()
	})
}

// SetValidatedAt sets the "validated_at" field.
func (u *CASBackendUpsertBulk) SetValidatedAt(v time.Time) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetValidatedAt(v)
	})
}

// UpdateValidatedAt sets the "validated_at" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateValidatedAt() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateValidatedAt()
	})
}

// SetDefault sets the "default" field.
func (u *CASBackendUpsertBulk) SetDefault(v bool) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetDefault(v)
	})
}

// UpdateDefault sets the "default" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateDefault() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateDefault()
	})
}

// SetDeletedAt sets the "deleted_at" field.
func (u *CASBackendUpsertBulk) SetDeletedAt(v time.Time) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetDeletedAt(v)
	})
}

// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateDeletedAt() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateDeletedAt()
	})
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *CASBackendUpsertBulk) ClearDeletedAt() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.ClearDeletedAt()
	})
}

// SetMaxBlobSizeBytes sets the "max_blob_size_bytes" field.
func (u *CASBackendUpsertBulk) SetMaxBlobSizeBytes(v int64) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.SetMaxBlobSizeBytes(v)
	})
}

// AddMaxBlobSizeBytes adds v to the "max_blob_size_bytes" field.
func (u *CASBackendUpsertBulk) AddMaxBlobSizeBytes(v int64) *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.AddMaxBlobSizeBytes(v)
	})
}

// UpdateMaxBlobSizeBytes sets the "max_blob_size_bytes" field to the value that was provided on create.
func (u *CASBackendUpsertBulk) UpdateMaxBlobSizeBytes() *CASBackendUpsertBulk {
	return u.Update(func(s *CASBackendUpsert) {
		s.UpdateMaxBlobSizeBytes()
	})
}

// Exec executes the query.
func (u *CASBackendUpsertBulk) Exec(ctx context.Context) error {
	if u.create.err != nil {
		return u.create.err
	}
	for i, b := range u.create.builders {
		if len(b.conflict) != 0 {
			return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the CASBackendCreateBulk instead", i)
		}
	}
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for CASBackendCreateBulk.OnConflict")
	}
	return u.create.Exec(ctx)
}

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