// 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/appditto/pippin_nano_wallet/libs/database/ent/account"
	"github.com/appditto/pippin_nano_wallet/libs/database/ent/block"
	"github.com/google/uuid"
)

// BlockCreate is the builder for creating a Block entity.
type BlockCreate struct {
	config
	mutation *BlockMutation
	hooks    []Hook
}

// SetAccountID sets the "account_id" field.
func (bc *BlockCreate) SetAccountID(u uuid.UUID) *BlockCreate {
	bc.mutation.SetAccountID(u)
	return bc
}

// SetNillableAccountID sets the "account_id" field if the given value is not nil.
func (bc *BlockCreate) SetNillableAccountID(u *uuid.UUID) *BlockCreate {
	if u != nil {
		bc.SetAccountID(*u)
	}
	return bc
}

// SetBlockHash sets the "block_hash" field.
func (bc *BlockCreate) SetBlockHash(s string) *BlockCreate {
	bc.mutation.SetBlockHash(s)
	return bc
}

// SetBlock sets the "block" field.
func (bc *BlockCreate) SetBlock(m map[string]interface{}) *BlockCreate {
	bc.mutation.SetBlock(m)
	return bc
}

// SetSendID sets the "send_id" field.
func (bc *BlockCreate) SetSendID(s string) *BlockCreate {
	bc.mutation.SetSendID(s)
	return bc
}

// SetNillableSendID sets the "send_id" field if the given value is not nil.
func (bc *BlockCreate) SetNillableSendID(s *string) *BlockCreate {
	if s != nil {
		bc.SetSendID(*s)
	}
	return bc
}

// SetSubtype sets the "subtype" field.
func (bc *BlockCreate) SetSubtype(s string) *BlockCreate {
	bc.mutation.SetSubtype(s)
	return bc
}

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

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

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

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

// SetAccount sets the "account" edge to the Account entity.
func (bc *BlockCreate) SetAccount(a *Account) *BlockCreate {
	return bc.SetAccountID(a.ID)
}

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

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

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

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

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

// defaults sets the default values of the builder before save.
func (bc *BlockCreate) defaults() {
	if _, ok := bc.mutation.CreatedAt(); !ok {
		v := block.DefaultCreatedAt()
		bc.mutation.SetCreatedAt(v)
	}
	if _, ok := bc.mutation.ID(); !ok {
		v := block.DefaultID()
		bc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (bc *BlockCreate) check() error {
	if _, ok := bc.mutation.BlockHash(); !ok {
		return &ValidationError{Name: "block_hash", err: errors.New(`ent: missing required field "Block.block_hash"`)}
	}
	if v, ok := bc.mutation.BlockHash(); ok {
		if err := block.BlockHashValidator(v); err != nil {
			return &ValidationError{Name: "block_hash", err: fmt.Errorf(`ent: validator failed for field "Block.block_hash": %w`, err)}
		}
	}
	if _, ok := bc.mutation.Block(); !ok {
		return &ValidationError{Name: "block", err: errors.New(`ent: missing required field "Block.block"`)}
	}
	if v, ok := bc.mutation.SendID(); ok {
		if err := block.SendIDValidator(v); err != nil {
			return &ValidationError{Name: "send_id", err: fmt.Errorf(`ent: validator failed for field "Block.send_id": %w`, err)}
		}
	}
	if _, ok := bc.mutation.Subtype(); !ok {
		return &ValidationError{Name: "subtype", err: errors.New(`ent: missing required field "Block.subtype"`)}
	}
	if v, ok := bc.mutation.Subtype(); ok {
		if err := block.SubtypeValidator(v); err != nil {
			return &ValidationError{Name: "subtype", err: fmt.Errorf(`ent: validator failed for field "Block.subtype": %w`, err)}
		}
	}
	if _, ok := bc.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Block.created_at"`)}
	}
	return nil
}

func (bc *BlockCreate) sqlSave(ctx context.Context) (*Block, error) {
	_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
	}
	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
		}
	}
	return _node, nil
}

func (bc *BlockCreate) createSpec() (*Block, *sqlgraph.CreateSpec) {
	var (
		_node = &Block{config: bc.config}
		_spec = &sqlgraph.CreateSpec{
			Table: block.Table,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeUUID,
				Column: block.FieldID,
			},
		}
	)
	if id, ok := bc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := bc.mutation.BlockHash(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: block.FieldBlockHash,
		})
		_node.BlockHash = value
	}
	if value, ok := bc.mutation.Block(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeJSON,
			Value:  value,
			Column: block.FieldBlock,
		})
		_node.Block = value
	}
	if value, ok := bc.mutation.SendID(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: block.FieldSendID,
		})
		_node.SendID = &value
	}
	if value, ok := bc.mutation.Subtype(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: block.FieldSubtype,
		})
		_node.Subtype = value
	}
	if value, ok := bc.mutation.CreatedAt(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: block.FieldCreatedAt,
		})
		_node.CreatedAt = value
	}
	if nodes := bc.mutation.AccountIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   block.AccountTable,
			Columns: []string{block.AccountColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeUUID,
					Column: account.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.AccountID = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// BlockCreateBulk is the builder for creating many Block entities in bulk.
type BlockCreateBulk struct {
	config
	builders []*BlockCreate
}

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

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

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