// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"

	"ariga.io/ogent/internal/integration/ogent/ent/hat"
	"ariga.io/ogent/internal/integration/ogent/ent/user"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// HatCreate is the builder for creating a Hat entity.
type HatCreate struct {
	config
	mutation *HatMutation
	hooks    []Hook
}

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

// SetType sets the "type" field.
func (hc *HatCreate) SetType(h hat.Type) *HatCreate {
	hc.mutation.SetType(h)
	return hc
}

// SetWearerID sets the "wearer" edge to the User entity by ID.
func (hc *HatCreate) SetWearerID(id int) *HatCreate {
	hc.mutation.SetWearerID(id)
	return hc
}

// SetNillableWearerID sets the "wearer" edge to the User entity by ID if the given value is not nil.
func (hc *HatCreate) SetNillableWearerID(id *int) *HatCreate {
	if id != nil {
		hc = hc.SetWearerID(*id)
	}
	return hc
}

// SetWearer sets the "wearer" edge to the User entity.
func (hc *HatCreate) SetWearer(u *User) *HatCreate {
	return hc.SetWearerID(u.ID)
}

// Mutation returns the HatMutation object of the builder.
func (hc *HatCreate) Mutation() *HatMutation {
	return hc.mutation
}

// Save creates the Hat in the database.
func (hc *HatCreate) Save(ctx context.Context) (*Hat, error) {
	return withHooks[*Hat, HatMutation](ctx, hc.sqlSave, hc.mutation, hc.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (hc *HatCreate) check() error {
	if _, ok := hc.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Hat.name"`)}
	}
	if _, ok := hc.mutation.GetType(); !ok {
		return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Hat.type"`)}
	}
	if v, ok := hc.mutation.GetType(); ok {
		if err := hat.TypeValidator(v); err != nil {
			return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Hat.type": %w`, err)}
		}
	}
	return nil
}

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

func (hc *HatCreate) createSpec() (*Hat, *sqlgraph.CreateSpec) {
	var (
		_node = &Hat{config: hc.config}
		_spec = sqlgraph.NewCreateSpec(hat.Table, sqlgraph.NewFieldSpec(hat.FieldID, field.TypeInt))
	)
	if value, ok := hc.mutation.Name(); ok {
		_spec.SetField(hat.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := hc.mutation.GetType(); ok {
		_spec.SetField(hat.FieldType, field.TypeEnum, value)
		_node.Type = value
	}
	if nodes := hc.mutation.WearerIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2O,
			Inverse: true,
			Table:   hat.WearerTable,
			Columns: []string{hat.WearerColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt,
					Column: user.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.user_favorite_hat = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// HatCreateBulk is the builder for creating many Hat entities in bulk.
type HatCreateBulk struct {
	config
	builders []*HatCreate
}

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

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

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

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