// Code generated by entc, DO NOT EDIT.

package ent

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

	"code.icod.de/postfix/manager/ent/account"
	"code.icod.de/postfix/manager/ent/alias"
	"code.icod.de/postfix/manager/ent/domain"
	"code.icod.de/postfix/manager/ent/logentry"
	"code.icod.de/postfix/manager/ent/mailbox"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// DomainCreate is the builder for creating a Domain entity.
type DomainCreate struct {
	config
	mutation *DomainMutation
	hooks    []Hook
}

// SetCreated sets the "created" field.
func (dc *DomainCreate) SetCreated(t time.Time) *DomainCreate {
	dc.mutation.SetCreated(t)
	return dc
}

// SetNillableCreated sets the "created" field if the given value is not nil.
func (dc *DomainCreate) SetNillableCreated(t *time.Time) *DomainCreate {
	if t != nil {
		dc.SetCreated(*t)
	}
	return dc
}

// SetModified sets the "modified" field.
func (dc *DomainCreate) SetModified(t time.Time) *DomainCreate {
	dc.mutation.SetModified(t)
	return dc
}

// SetNillableModified sets the "modified" field if the given value is not nil.
func (dc *DomainCreate) SetNillableModified(t *time.Time) *DomainCreate {
	if t != nil {
		dc.SetModified(*t)
	}
	return dc
}

// SetDomain sets the "domain" field.
func (dc *DomainCreate) SetDomain(s string) *DomainCreate {
	dc.mutation.SetDomain(s)
	return dc
}

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

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

// SetMaxAliases sets the "max_aliases" field.
func (dc *DomainCreate) SetMaxAliases(i int64) *DomainCreate {
	dc.mutation.SetMaxAliases(i)
	return dc
}

// SetMaxMailboxes sets the "max_mailboxes" field.
func (dc *DomainCreate) SetMaxMailboxes(i int64) *DomainCreate {
	dc.mutation.SetMaxMailboxes(i)
	return dc
}

// SetMaxQuota sets the "max_quota" field.
func (dc *DomainCreate) SetMaxQuota(i int64) *DomainCreate {
	dc.mutation.SetMaxQuota(i)
	return dc
}

// SetQuota sets the "quota" field.
func (dc *DomainCreate) SetQuota(i int64) *DomainCreate {
	dc.mutation.SetQuota(i)
	return dc
}

// SetTransport sets the "transport" field.
func (dc *DomainCreate) SetTransport(s string) *DomainCreate {
	dc.mutation.SetTransport(s)
	return dc
}

// SetBackupMx sets the "backup_mx" field.
func (dc *DomainCreate) SetBackupMx(b bool) *DomainCreate {
	dc.mutation.SetBackupMx(b)
	return dc
}

// SetActive sets the "active" field.
func (dc *DomainCreate) SetActive(b bool) *DomainCreate {
	dc.mutation.SetActive(b)
	return dc
}

// SetID sets the "id" field.
func (dc *DomainCreate) SetID(i int64) *DomainCreate {
	dc.mutation.SetID(i)
	return dc
}

// AddMailboxIDs adds the "mailboxes" edge to the Mailbox entity by IDs.
func (dc *DomainCreate) AddMailboxIDs(ids ...int64) *DomainCreate {
	dc.mutation.AddMailboxIDs(ids...)
	return dc
}

// AddMailboxes adds the "mailboxes" edges to the Mailbox entity.
func (dc *DomainCreate) AddMailboxes(m ...*Mailbox) *DomainCreate {
	ids := make([]int64, len(m))
	for i := range m {
		ids[i] = m[i].ID
	}
	return dc.AddMailboxIDs(ids...)
}

// AddAliasIDs adds the "aliases" edge to the Alias entity by IDs.
func (dc *DomainCreate) AddAliasIDs(ids ...int64) *DomainCreate {
	dc.mutation.AddAliasIDs(ids...)
	return dc
}

// AddAliases adds the "aliases" edges to the Alias entity.
func (dc *DomainCreate) AddAliases(a ...*Alias) *DomainCreate {
	ids := make([]int64, len(a))
	for i := range a {
		ids[i] = a[i].ID
	}
	return dc.AddAliasIDs(ids...)
}

// AddLogIDs adds the "logs" edge to the Logentry entity by IDs.
func (dc *DomainCreate) AddLogIDs(ids ...int64) *DomainCreate {
	dc.mutation.AddLogIDs(ids...)
	return dc
}

// AddLogs adds the "logs" edges to the Logentry entity.
func (dc *DomainCreate) AddLogs(l ...*Logentry) *DomainCreate {
	ids := make([]int64, len(l))
	for i := range l {
		ids[i] = l[i].ID
	}
	return dc.AddLogIDs(ids...)
}

// AddAccountIDs adds the "accounts" edge to the Account entity by IDs.
func (dc *DomainCreate) AddAccountIDs(ids ...int64) *DomainCreate {
	dc.mutation.AddAccountIDs(ids...)
	return dc
}

// AddAccounts adds the "accounts" edges to the Account entity.
func (dc *DomainCreate) AddAccounts(a ...*Account) *DomainCreate {
	ids := make([]int64, len(a))
	for i := range a {
		ids[i] = a[i].ID
	}
	return dc.AddAccountIDs(ids...)
}

// Mutation returns the DomainMutation object of the builder.
func (dc *DomainCreate) Mutation() *DomainMutation {
	return dc.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (dc *DomainCreate) defaults() {
	if _, ok := dc.mutation.Created(); !ok {
		v := domain.DefaultCreated()
		dc.mutation.SetCreated(v)
	}
	if _, ok := dc.mutation.Modified(); !ok {
		v := domain.DefaultModified()
		dc.mutation.SetModified(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (dc *DomainCreate) check() error {
	if _, ok := dc.mutation.Created(); !ok {
		return &ValidationError{Name: "created", err: errors.New(`ent: missing required field "Domain.created"`)}
	}
	if _, ok := dc.mutation.Domain(); !ok {
		return &ValidationError{Name: "domain", err: errors.New(`ent: missing required field "Domain.domain"`)}
	}
	if _, ok := dc.mutation.MaxAliases(); !ok {
		return &ValidationError{Name: "max_aliases", err: errors.New(`ent: missing required field "Domain.max_aliases"`)}
	}
	if _, ok := dc.mutation.MaxMailboxes(); !ok {
		return &ValidationError{Name: "max_mailboxes", err: errors.New(`ent: missing required field "Domain.max_mailboxes"`)}
	}
	if _, ok := dc.mutation.MaxQuota(); !ok {
		return &ValidationError{Name: "max_quota", err: errors.New(`ent: missing required field "Domain.max_quota"`)}
	}
	if _, ok := dc.mutation.Quota(); !ok {
		return &ValidationError{Name: "quota", err: errors.New(`ent: missing required field "Domain.quota"`)}
	}
	if _, ok := dc.mutation.Transport(); !ok {
		return &ValidationError{Name: "transport", err: errors.New(`ent: missing required field "Domain.transport"`)}
	}
	if _, ok := dc.mutation.BackupMx(); !ok {
		return &ValidationError{Name: "backup_mx", err: errors.New(`ent: missing required field "Domain.backup_mx"`)}
	}
	if _, ok := dc.mutation.Active(); !ok {
		return &ValidationError{Name: "active", err: errors.New(`ent: missing required field "Domain.active"`)}
	}
	return nil
}

func (dc *DomainCreate) sqlSave(ctx context.Context) (*Domain, error) {
	_node, _spec := dc.createSpec()
	if err := sqlgraph.CreateNode(ctx, dc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{err.Error(), err}
		}
		return nil, err
	}
	if _spec.ID.Value != _node.ID {
		id := _spec.ID.Value.(int64)
		_node.ID = int64(id)
	}
	return _node, nil
}

func (dc *DomainCreate) createSpec() (*Domain, *sqlgraph.CreateSpec) {
	var (
		_node = &Domain{config: dc.config}
		_spec = &sqlgraph.CreateSpec{
			Table: domain.Table,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeInt64,
				Column: domain.FieldID,
			},
		}
	)
	if id, ok := dc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = id
	}
	if value, ok := dc.mutation.Created(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: domain.FieldCreated,
		})
		_node.Created = value
	}
	if value, ok := dc.mutation.Modified(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: domain.FieldModified,
		})
		_node.Modified = &value
	}
	if value, ok := dc.mutation.Domain(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: domain.FieldDomain,
		})
		_node.Domain = value
	}
	if value, ok := dc.mutation.Description(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: domain.FieldDescription,
		})
		_node.Description = &value
	}
	if value, ok := dc.mutation.MaxAliases(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeInt64,
			Value:  value,
			Column: domain.FieldMaxAliases,
		})
		_node.MaxAliases = value
	}
	if value, ok := dc.mutation.MaxMailboxes(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeInt64,
			Value:  value,
			Column: domain.FieldMaxMailboxes,
		})
		_node.MaxMailboxes = value
	}
	if value, ok := dc.mutation.MaxQuota(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeInt64,
			Value:  value,
			Column: domain.FieldMaxQuota,
		})
		_node.MaxQuota = value
	}
	if value, ok := dc.mutation.Quota(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeInt64,
			Value:  value,
			Column: domain.FieldQuota,
		})
		_node.Quota = value
	}
	if value, ok := dc.mutation.Transport(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: domain.FieldTransport,
		})
		_node.Transport = value
	}
	if value, ok := dc.mutation.BackupMx(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeBool,
			Value:  value,
			Column: domain.FieldBackupMx,
		})
		_node.BackupMx = value
	}
	if value, ok := dc.mutation.Active(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeBool,
			Value:  value,
			Column: domain.FieldActive,
		})
		_node.Active = value
	}
	if nodes := dc.mutation.MailboxesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   domain.MailboxesTable,
			Columns: []string{domain.MailboxesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt64,
					Column: mailbox.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := dc.mutation.AliasesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   domain.AliasesTable,
			Columns: []string{domain.AliasesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt64,
					Column: alias.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := dc.mutation.LogsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   domain.LogsTable,
			Columns: []string{domain.LogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt64,
					Column: logentry.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := dc.mutation.AccountsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   domain.AccountsTable,
			Columns: domain.AccountsPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt64,
					Column: account.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// DomainCreateBulk is the builder for creating many Domain entities in bulk.
type DomainCreateBulk struct {
	config
	builders []*DomainCreate
}

// Save creates the Domain entities in the database.
func (dcb *DomainCreateBulk) Save(ctx context.Context) ([]*Domain, error) {
	specs := make([]*sqlgraph.CreateSpec, len(dcb.builders))
	nodes := make([]*Domain, len(dcb.builders))
	mutators := make([]Mutator, len(dcb.builders))
	for i := range dcb.builders {
		func(i int, root context.Context) {
			builder := dcb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*DomainMutation)
				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, dcb.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, dcb.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
				if specs[i].ID.Value != nil && nodes[i].ID == 0 {
					id := specs[i].ID.Value.(int64)
					nodes[i].ID = int64(id)
				}
				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, dcb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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