// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/buildbarn/bb-portal/ent/gen/ent/bazelinvocation"
	"github.com/buildbarn/bb-portal/ent/gen/ent/build"
	"github.com/google/uuid"
)

// BuildCreate is the builder for creating a Build entity.
type BuildCreate struct {
	config
	mutation *BuildMutation
	hooks    []Hook
}

// SetBuildURL sets the "build_url" field.
func (bc *BuildCreate) SetBuildURL(s string) *BuildCreate {
	bc.mutation.SetBuildURL(s)
	return bc
}

// SetBuildUUID sets the "build_uuid" field.
func (bc *BuildCreate) SetBuildUUID(u uuid.UUID) *BuildCreate {
	bc.mutation.SetBuildUUID(u)
	return bc
}

// SetEnv sets the "env" field.
func (bc *BuildCreate) SetEnv(m map[string]string) *BuildCreate {
	bc.mutation.SetEnv(m)
	return bc
}

// SetTimestamp sets the "timestamp" field.
func (bc *BuildCreate) SetTimestamp(t time.Time) *BuildCreate {
	bc.mutation.SetTimestamp(t)
	return bc
}

// SetNillableTimestamp sets the "timestamp" field if the given value is not nil.
func (bc *BuildCreate) SetNillableTimestamp(t *time.Time) *BuildCreate {
	if t != nil {
		bc.SetTimestamp(*t)
	}
	return bc
}

// AddInvocationIDs adds the "invocations" edge to the BazelInvocation entity by IDs.
func (bc *BuildCreate) AddInvocationIDs(ids ...int) *BuildCreate {
	bc.mutation.AddInvocationIDs(ids...)
	return bc
}

// AddInvocations adds the "invocations" edges to the BazelInvocation entity.
func (bc *BuildCreate) AddInvocations(b ...*BazelInvocation) *BuildCreate {
	ids := make([]int, len(b))
	for i := range b {
		ids[i] = b[i].ID
	}
	return bc.AddInvocationIDs(ids...)
}

// Mutation returns the BuildMutation object of the builder.
func (bc *BuildCreate) Mutation() *BuildMutation {
	return bc.mutation
}

// Save creates the Build in the database.
func (bc *BuildCreate) Save(ctx context.Context) (*Build, error) {
	return withHooks(ctx, bc.sqlSave, bc.mutation, bc.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (bc *BuildCreate) check() error {
	if _, ok := bc.mutation.BuildURL(); !ok {
		return &ValidationError{Name: "build_url", err: errors.New(`ent: missing required field "Build.build_url"`)}
	}
	if _, ok := bc.mutation.BuildUUID(); !ok {
		return &ValidationError{Name: "build_uuid", err: errors.New(`ent: missing required field "Build.build_uuid"`)}
	}
	if _, ok := bc.mutation.Env(); !ok {
		return &ValidationError{Name: "env", err: errors.New(`ent: missing required field "Build.env"`)}
	}
	return nil
}

func (bc *BuildCreate) sqlSave(ctx context.Context) (*Build, error) {
	if err := bc.check(); err != nil {
		return nil, err
	}
	_node, _spec := bc.createSpec()
	if err := sqlgraph.CreateNode(ctx, bc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	id := _spec.ID.Value.(int64)
	_node.ID = int(id)
	bc.mutation.id = &_node.ID
	bc.mutation.done = true
	return _node, nil
}

func (bc *BuildCreate) createSpec() (*Build, *sqlgraph.CreateSpec) {
	var (
		_node = &Build{config: bc.config}
		_spec = sqlgraph.NewCreateSpec(build.Table, sqlgraph.NewFieldSpec(build.FieldID, field.TypeInt))
	)
	if value, ok := bc.mutation.BuildURL(); ok {
		_spec.SetField(build.FieldBuildURL, field.TypeString, value)
		_node.BuildURL = value
	}
	if value, ok := bc.mutation.BuildUUID(); ok {
		_spec.SetField(build.FieldBuildUUID, field.TypeUUID, value)
		_node.BuildUUID = value
	}
	if value, ok := bc.mutation.Env(); ok {
		_spec.SetField(build.FieldEnv, field.TypeJSON, value)
		_node.Env = value
	}
	if value, ok := bc.mutation.Timestamp(); ok {
		_spec.SetField(build.FieldTimestamp, field.TypeTime, value)
		_node.Timestamp = value
	}
	if nodes := bc.mutation.InvocationsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   build.InvocationsTable,
			Columns: []string{build.InvocationsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(bazelinvocation.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// BuildCreateBulk is the builder for creating many Build entities in bulk.
type BuildCreateBulk struct {
	config
	err      error
	builders []*BuildCreate
}

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

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

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

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