// 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/data/ent/apitoken"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/casbackend"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/group"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/integration"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/membership"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/organization"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/project"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontract"
	"github.com/google/uuid"
)

// OrganizationCreate is the builder for creating a Organization entity.
type OrganizationCreate struct {
	config
	mutation *OrganizationMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

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

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

// SetUpdatedAt sets the "updated_at" field.
func (oc *OrganizationCreate) SetUpdatedAt(t time.Time) *OrganizationCreate {
	oc.mutation.SetUpdatedAt(t)
	return oc
}

// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (oc *OrganizationCreate) SetNillableUpdatedAt(t *time.Time) *OrganizationCreate {
	if t != nil {
		oc.SetUpdatedAt(*t)
	}
	return oc
}

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

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

// SetBlockOnPolicyViolation sets the "block_on_policy_violation" field.
func (oc *OrganizationCreate) SetBlockOnPolicyViolation(b bool) *OrganizationCreate {
	oc.mutation.SetBlockOnPolicyViolation(b)
	return oc
}

// SetNillableBlockOnPolicyViolation sets the "block_on_policy_violation" field if the given value is not nil.
func (oc *OrganizationCreate) SetNillableBlockOnPolicyViolation(b *bool) *OrganizationCreate {
	if b != nil {
		oc.SetBlockOnPolicyViolation(*b)
	}
	return oc
}

// SetPoliciesAllowedHostnames sets the "policies_allowed_hostnames" field.
func (oc *OrganizationCreate) SetPoliciesAllowedHostnames(s []string) *OrganizationCreate {
	oc.mutation.SetPoliciesAllowedHostnames(s)
	return oc
}

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

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

// AddMembershipIDs adds the "memberships" edge to the Membership entity by IDs.
func (oc *OrganizationCreate) AddMembershipIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddMembershipIDs(ids...)
	return oc
}

// AddMemberships adds the "memberships" edges to the Membership entity.
func (oc *OrganizationCreate) AddMemberships(m ...*Membership) *OrganizationCreate {
	ids := make([]uuid.UUID, len(m))
	for i := range m {
		ids[i] = m[i].ID
	}
	return oc.AddMembershipIDs(ids...)
}

// AddWorkflowContractIDs adds the "workflow_contracts" edge to the WorkflowContract entity by IDs.
func (oc *OrganizationCreate) AddWorkflowContractIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddWorkflowContractIDs(ids...)
	return oc
}

// AddWorkflowContracts adds the "workflow_contracts" edges to the WorkflowContract entity.
func (oc *OrganizationCreate) AddWorkflowContracts(w ...*WorkflowContract) *OrganizationCreate {
	ids := make([]uuid.UUID, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return oc.AddWorkflowContractIDs(ids...)
}

// AddWorkflowIDs adds the "workflows" edge to the Workflow entity by IDs.
func (oc *OrganizationCreate) AddWorkflowIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddWorkflowIDs(ids...)
	return oc
}

// AddWorkflows adds the "workflows" edges to the Workflow entity.
func (oc *OrganizationCreate) AddWorkflows(w ...*Workflow) *OrganizationCreate {
	ids := make([]uuid.UUID, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return oc.AddWorkflowIDs(ids...)
}

// AddCasBackendIDs adds the "cas_backends" edge to the CASBackend entity by IDs.
func (oc *OrganizationCreate) AddCasBackendIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddCasBackendIDs(ids...)
	return oc
}

// AddCasBackends adds the "cas_backends" edges to the CASBackend entity.
func (oc *OrganizationCreate) AddCasBackends(c ...*CASBackend) *OrganizationCreate {
	ids := make([]uuid.UUID, len(c))
	for i := range c {
		ids[i] = c[i].ID
	}
	return oc.AddCasBackendIDs(ids...)
}

// AddIntegrationIDs adds the "integrations" edge to the Integration entity by IDs.
func (oc *OrganizationCreate) AddIntegrationIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddIntegrationIDs(ids...)
	return oc
}

// AddIntegrations adds the "integrations" edges to the Integration entity.
func (oc *OrganizationCreate) AddIntegrations(i ...*Integration) *OrganizationCreate {
	ids := make([]uuid.UUID, len(i))
	for j := range i {
		ids[j] = i[j].ID
	}
	return oc.AddIntegrationIDs(ids...)
}

// AddAPITokenIDs adds the "api_tokens" edge to the APIToken entity by IDs.
func (oc *OrganizationCreate) AddAPITokenIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddAPITokenIDs(ids...)
	return oc
}

// AddAPITokens adds the "api_tokens" edges to the APIToken entity.
func (oc *OrganizationCreate) AddAPITokens(a ...*APIToken) *OrganizationCreate {
	ids := make([]uuid.UUID, len(a))
	for i := range a {
		ids[i] = a[i].ID
	}
	return oc.AddAPITokenIDs(ids...)
}

// AddProjectIDs adds the "projects" edge to the Project entity by IDs.
func (oc *OrganizationCreate) AddProjectIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddProjectIDs(ids...)
	return oc
}

// AddProjects adds the "projects" edges to the Project entity.
func (oc *OrganizationCreate) AddProjects(p ...*Project) *OrganizationCreate {
	ids := make([]uuid.UUID, len(p))
	for i := range p {
		ids[i] = p[i].ID
	}
	return oc.AddProjectIDs(ids...)
}

// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (oc *OrganizationCreate) AddGroupIDs(ids ...uuid.UUID) *OrganizationCreate {
	oc.mutation.AddGroupIDs(ids...)
	return oc
}

// AddGroups adds the "groups" edges to the Group entity.
func (oc *OrganizationCreate) AddGroups(g ...*Group) *OrganizationCreate {
	ids := make([]uuid.UUID, len(g))
	for i := range g {
		ids[i] = g[i].ID
	}
	return oc.AddGroupIDs(ids...)
}

// Mutation returns the OrganizationMutation object of the builder.
func (oc *OrganizationCreate) Mutation() *OrganizationMutation {
	return oc.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (oc *OrganizationCreate) defaults() {
	if _, ok := oc.mutation.CreatedAt(); !ok {
		v := organization.DefaultCreatedAt()
		oc.mutation.SetCreatedAt(v)
	}
	if _, ok := oc.mutation.UpdatedAt(); !ok {
		v := organization.DefaultUpdatedAt()
		oc.mutation.SetUpdatedAt(v)
	}
	if _, ok := oc.mutation.BlockOnPolicyViolation(); !ok {
		v := organization.DefaultBlockOnPolicyViolation
		oc.mutation.SetBlockOnPolicyViolation(v)
	}
	if _, ok := oc.mutation.ID(); !ok {
		v := organization.DefaultID()
		oc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (oc *OrganizationCreate) check() error {
	if _, ok := oc.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Organization.name"`)}
	}
	if _, ok := oc.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Organization.created_at"`)}
	}
	if _, ok := oc.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Organization.updated_at"`)}
	}
	if _, ok := oc.mutation.BlockOnPolicyViolation(); !ok {
		return &ValidationError{Name: "block_on_policy_violation", err: errors.New(`ent: missing required field "Organization.block_on_policy_violation"`)}
	}
	return nil
}

func (oc *OrganizationCreate) sqlSave(ctx context.Context) (*Organization, error) {
	if err := oc.check(); err != nil {
		return nil, err
	}
	_node, _spec := oc.createSpec()
	if err := sqlgraph.CreateNode(ctx, oc.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
		}
	}
	oc.mutation.id = &_node.ID
	oc.mutation.done = true
	return _node, nil
}

func (oc *OrganizationCreate) createSpec() (*Organization, *sqlgraph.CreateSpec) {
	var (
		_node = &Organization{config: oc.config}
		_spec = sqlgraph.NewCreateSpec(organization.Table, sqlgraph.NewFieldSpec(organization.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = oc.conflict
	if id, ok := oc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := oc.mutation.Name(); ok {
		_spec.SetField(organization.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := oc.mutation.CreatedAt(); ok {
		_spec.SetField(organization.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := oc.mutation.UpdatedAt(); ok {
		_spec.SetField(organization.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if value, ok := oc.mutation.DeletedAt(); ok {
		_spec.SetField(organization.FieldDeletedAt, field.TypeTime, value)
		_node.DeletedAt = value
	}
	if value, ok := oc.mutation.BlockOnPolicyViolation(); ok {
		_spec.SetField(organization.FieldBlockOnPolicyViolation, field.TypeBool, value)
		_node.BlockOnPolicyViolation = value
	}
	if value, ok := oc.mutation.PoliciesAllowedHostnames(); ok {
		_spec.SetField(organization.FieldPoliciesAllowedHostnames, field.TypeJSON, value)
		_node.PoliciesAllowedHostnames = value
	}
	if nodes := oc.mutation.MembershipsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.MembershipsTable,
			Columns: []string{organization.MembershipsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(membership.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := oc.mutation.WorkflowContractsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.WorkflowContractsTable,
			Columns: []string{organization.WorkflowContractsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(workflowcontract.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := oc.mutation.WorkflowsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.WorkflowsTable,
			Columns: []string{organization.WorkflowsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(workflow.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := oc.mutation.CasBackendsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.CasBackendsTable,
			Columns: []string{organization.CasBackendsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(casbackend.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := oc.mutation.IntegrationsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.IntegrationsTable,
			Columns: []string{organization.IntegrationsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(integration.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := oc.mutation.APITokensIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.APITokensTable,
			Columns: []string{organization.APITokensColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(apitoken.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := oc.mutation.ProjectsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.ProjectsTable,
			Columns: []string{organization.ProjectsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := oc.mutation.GroupsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   organization.GroupsTable,
			Columns: []string{organization.GroupsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(group.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.Organization.Create().
//		SetName(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.OrganizationUpsert) {
//			SetName(v+v).
//		}).
//		Exec(ctx)
func (oc *OrganizationCreate) OnConflict(opts ...sql.ConflictOption) *OrganizationUpsertOne {
	oc.conflict = opts
	return &OrganizationUpsertOne{
		create: oc,
	}
}

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

type (
	// OrganizationUpsertOne is the builder for "upsert"-ing
	//  one Organization node.
	OrganizationUpsertOne struct {
		create *OrganizationCreate
	}

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

// SetName sets the "name" field.
func (u *OrganizationUpsert) SetName(v string) *OrganizationUpsert {
	u.Set(organization.FieldName, v)
	return u
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *OrganizationUpsert) UpdateName() *OrganizationUpsert {
	u.SetExcluded(organization.FieldName)
	return u
}

// SetUpdatedAt sets the "updated_at" field.
func (u *OrganizationUpsert) SetUpdatedAt(v time.Time) *OrganizationUpsert {
	u.Set(organization.FieldUpdatedAt, v)
	return u
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *OrganizationUpsert) UpdateUpdatedAt() *OrganizationUpsert {
	u.SetExcluded(organization.FieldUpdatedAt)
	return u
}

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

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

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

// SetBlockOnPolicyViolation sets the "block_on_policy_violation" field.
func (u *OrganizationUpsert) SetBlockOnPolicyViolation(v bool) *OrganizationUpsert {
	u.Set(organization.FieldBlockOnPolicyViolation, v)
	return u
}

// UpdateBlockOnPolicyViolation sets the "block_on_policy_violation" field to the value that was provided on create.
func (u *OrganizationUpsert) UpdateBlockOnPolicyViolation() *OrganizationUpsert {
	u.SetExcluded(organization.FieldBlockOnPolicyViolation)
	return u
}

// SetPoliciesAllowedHostnames sets the "policies_allowed_hostnames" field.
func (u *OrganizationUpsert) SetPoliciesAllowedHostnames(v []string) *OrganizationUpsert {
	u.Set(organization.FieldPoliciesAllowedHostnames, v)
	return u
}

// UpdatePoliciesAllowedHostnames sets the "policies_allowed_hostnames" field to the value that was provided on create.
func (u *OrganizationUpsert) UpdatePoliciesAllowedHostnames() *OrganizationUpsert {
	u.SetExcluded(organization.FieldPoliciesAllowedHostnames)
	return u
}

// ClearPoliciesAllowedHostnames clears the value of the "policies_allowed_hostnames" field.
func (u *OrganizationUpsert) ClearPoliciesAllowedHostnames() *OrganizationUpsert {
	u.SetNull(organization.FieldPoliciesAllowedHostnames)
	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.Organization.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(organization.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *OrganizationUpsertOne) UpdateNewValues() *OrganizationUpsertOne {
	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(organization.FieldID)
		}
		if _, exists := u.create.mutation.CreatedAt(); exists {
			s.SetIgnore(organization.FieldCreatedAt)
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Organization.Create().
//	    OnConflict(sql.ResolveWithIgnore()).
//	    Exec(ctx)
func (u *OrganizationUpsertOne) Ignore() *OrganizationUpsertOne {
	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 *OrganizationUpsertOne) DoNothing() *OrganizationUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

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

// SetName sets the "name" field.
func (u *OrganizationUpsertOne) SetName(v string) *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *OrganizationUpsertOne) UpdateName() *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdateName()
	})
}

// SetUpdatedAt sets the "updated_at" field.
func (u *OrganizationUpsertOne) SetUpdatedAt(v time.Time) *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetUpdatedAt(v)
	})
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *OrganizationUpsertOne) UpdateUpdatedAt() *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdateUpdatedAt()
	})
}

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

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

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

// SetBlockOnPolicyViolation sets the "block_on_policy_violation" field.
func (u *OrganizationUpsertOne) SetBlockOnPolicyViolation(v bool) *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetBlockOnPolicyViolation(v)
	})
}

// UpdateBlockOnPolicyViolation sets the "block_on_policy_violation" field to the value that was provided on create.
func (u *OrganizationUpsertOne) UpdateBlockOnPolicyViolation() *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdateBlockOnPolicyViolation()
	})
}

// SetPoliciesAllowedHostnames sets the "policies_allowed_hostnames" field.
func (u *OrganizationUpsertOne) SetPoliciesAllowedHostnames(v []string) *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetPoliciesAllowedHostnames(v)
	})
}

// UpdatePoliciesAllowedHostnames sets the "policies_allowed_hostnames" field to the value that was provided on create.
func (u *OrganizationUpsertOne) UpdatePoliciesAllowedHostnames() *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdatePoliciesAllowedHostnames()
	})
}

// ClearPoliciesAllowedHostnames clears the value of the "policies_allowed_hostnames" field.
func (u *OrganizationUpsertOne) ClearPoliciesAllowedHostnames() *OrganizationUpsertOne {
	return u.Update(func(s *OrganizationUpsert) {
		s.ClearPoliciesAllowedHostnames()
	})
}

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

// ExecX is like Exec, but panics if an error occurs.
func (u *OrganizationUpsertOne) 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 *OrganizationUpsertOne) 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: OrganizationUpsertOne.ID is not supported by MySQL driver. Use OrganizationUpsertOne.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 *OrganizationUpsertOne) IDX(ctx context.Context) uuid.UUID {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

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

// Save creates the Organization entities in the database.
func (ocb *OrganizationCreateBulk) Save(ctx context.Context) ([]*Organization, error) {
	if ocb.err != nil {
		return nil, ocb.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(ocb.builders))
	nodes := make([]*Organization, len(ocb.builders))
	mutators := make([]Mutator, len(ocb.builders))
	for i := range ocb.builders {
		func(i int, root context.Context) {
			builder := ocb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*OrganizationMutation)
				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, ocb.builders[i+1].mutation)
				} else {
					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
					spec.OnConflict = ocb.conflict
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, ocb.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, ocb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Organization.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.OrganizationUpsert) {
//			SetName(v+v).
//		}).
//		Exec(ctx)
func (ocb *OrganizationCreateBulk) OnConflict(opts ...sql.ConflictOption) *OrganizationUpsertBulk {
	ocb.conflict = opts
	return &OrganizationUpsertBulk{
		create: ocb,
	}
}

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

// OrganizationUpsertBulk is the builder for "upsert"-ing
// a bulk of Organization nodes.
type OrganizationUpsertBulk struct {
	create *OrganizationCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.Organization.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(organization.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *OrganizationUpsertBulk) UpdateNewValues() *OrganizationUpsertBulk {
	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(organization.FieldID)
			}
			if _, exists := b.mutation.CreatedAt(); exists {
				s.SetIgnore(organization.FieldCreatedAt)
			}
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Organization.Create().
//		OnConflict(sql.ResolveWithIgnore()).
//		Exec(ctx)
func (u *OrganizationUpsertBulk) Ignore() *OrganizationUpsertBulk {
	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 *OrganizationUpsertBulk) DoNothing() *OrganizationUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

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

// SetName sets the "name" field.
func (u *OrganizationUpsertBulk) SetName(v string) *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *OrganizationUpsertBulk) UpdateName() *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdateName()
	})
}

// SetUpdatedAt sets the "updated_at" field.
func (u *OrganizationUpsertBulk) SetUpdatedAt(v time.Time) *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetUpdatedAt(v)
	})
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *OrganizationUpsertBulk) UpdateUpdatedAt() *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdateUpdatedAt()
	})
}

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

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

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

// SetBlockOnPolicyViolation sets the "block_on_policy_violation" field.
func (u *OrganizationUpsertBulk) SetBlockOnPolicyViolation(v bool) *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetBlockOnPolicyViolation(v)
	})
}

// UpdateBlockOnPolicyViolation sets the "block_on_policy_violation" field to the value that was provided on create.
func (u *OrganizationUpsertBulk) UpdateBlockOnPolicyViolation() *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdateBlockOnPolicyViolation()
	})
}

// SetPoliciesAllowedHostnames sets the "policies_allowed_hostnames" field.
func (u *OrganizationUpsertBulk) SetPoliciesAllowedHostnames(v []string) *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.SetPoliciesAllowedHostnames(v)
	})
}

// UpdatePoliciesAllowedHostnames sets the "policies_allowed_hostnames" field to the value that was provided on create.
func (u *OrganizationUpsertBulk) UpdatePoliciesAllowedHostnames() *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.UpdatePoliciesAllowedHostnames()
	})
}

// ClearPoliciesAllowedHostnames clears the value of the "policies_allowed_hostnames" field.
func (u *OrganizationUpsertBulk) ClearPoliciesAllowedHostnames() *OrganizationUpsertBulk {
	return u.Update(func(s *OrganizationUpsert) {
		s.ClearPoliciesAllowedHostnames()
	})
}

// Exec executes the query.
func (u *OrganizationUpsertBulk) 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 OrganizationCreateBulk instead", i)
		}
	}
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for OrganizationCreateBulk.OnConflict")
	}
	return u.create.Exec(ctx)
}

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