// 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/google/uuid"
	"github.com/lightsparkdev/spark/so/ent/paymentintent"
	"github.com/lightsparkdev/spark/so/ent/tokentransaction"
	"github.com/lightsparkdev/spark/so/ent/transfer"
)

// PaymentIntentCreate is the builder for creating a PaymentIntent entity.
type PaymentIntentCreate struct {
	config
	mutation *PaymentIntentMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetCreateTime sets the "create_time" field.
func (pic *PaymentIntentCreate) SetCreateTime(t time.Time) *PaymentIntentCreate {
	pic.mutation.SetCreateTime(t)
	return pic
}

// SetNillableCreateTime sets the "create_time" field if the given value is not nil.
func (pic *PaymentIntentCreate) SetNillableCreateTime(t *time.Time) *PaymentIntentCreate {
	if t != nil {
		pic.SetCreateTime(*t)
	}
	return pic
}

// SetUpdateTime sets the "update_time" field.
func (pic *PaymentIntentCreate) SetUpdateTime(t time.Time) *PaymentIntentCreate {
	pic.mutation.SetUpdateTime(t)
	return pic
}

// SetNillableUpdateTime sets the "update_time" field if the given value is not nil.
func (pic *PaymentIntentCreate) SetNillableUpdateTime(t *time.Time) *PaymentIntentCreate {
	if t != nil {
		pic.SetUpdateTime(*t)
	}
	return pic
}

// SetPaymentIntent sets the "payment_intent" field.
func (pic *PaymentIntentCreate) SetPaymentIntent(s string) *PaymentIntentCreate {
	pic.mutation.SetPaymentIntent(s)
	return pic
}

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

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

// AddTransferIDs adds the "transfer" edge to the Transfer entity by IDs.
func (pic *PaymentIntentCreate) AddTransferIDs(ids ...uuid.UUID) *PaymentIntentCreate {
	pic.mutation.AddTransferIDs(ids...)
	return pic
}

// AddTransfer adds the "transfer" edges to the Transfer entity.
func (pic *PaymentIntentCreate) AddTransfer(t ...*Transfer) *PaymentIntentCreate {
	ids := make([]uuid.UUID, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return pic.AddTransferIDs(ids...)
}

// AddTokenTransactionIDs adds the "token_transaction" edge to the TokenTransaction entity by IDs.
func (pic *PaymentIntentCreate) AddTokenTransactionIDs(ids ...uuid.UUID) *PaymentIntentCreate {
	pic.mutation.AddTokenTransactionIDs(ids...)
	return pic
}

// AddTokenTransaction adds the "token_transaction" edges to the TokenTransaction entity.
func (pic *PaymentIntentCreate) AddTokenTransaction(t ...*TokenTransaction) *PaymentIntentCreate {
	ids := make([]uuid.UUID, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return pic.AddTokenTransactionIDs(ids...)
}

// Mutation returns the PaymentIntentMutation object of the builder.
func (pic *PaymentIntentCreate) Mutation() *PaymentIntentMutation {
	return pic.mutation
}

// Save creates the PaymentIntent in the database.
func (pic *PaymentIntentCreate) Save(ctx context.Context) (*PaymentIntent, error) {
	if err := pic.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, pic.sqlSave, pic.mutation, pic.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (pic *PaymentIntentCreate) defaults() error {
	if _, ok := pic.mutation.CreateTime(); !ok {
		if paymentintent.DefaultCreateTime == nil {
			return fmt.Errorf("ent: uninitialized paymentintent.DefaultCreateTime (forgotten import ent/runtime?)")
		}
		v := paymentintent.DefaultCreateTime()
		pic.mutation.SetCreateTime(v)
	}
	if _, ok := pic.mutation.UpdateTime(); !ok {
		if paymentintent.DefaultUpdateTime == nil {
			return fmt.Errorf("ent: uninitialized paymentintent.DefaultUpdateTime (forgotten import ent/runtime?)")
		}
		v := paymentintent.DefaultUpdateTime()
		pic.mutation.SetUpdateTime(v)
	}
	if _, ok := pic.mutation.ID(); !ok {
		if paymentintent.DefaultID == nil {
			return fmt.Errorf("ent: uninitialized paymentintent.DefaultID (forgotten import ent/runtime?)")
		}
		v := paymentintent.DefaultID()
		pic.mutation.SetID(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (pic *PaymentIntentCreate) check() error {
	if _, ok := pic.mutation.CreateTime(); !ok {
		return &ValidationError{Name: "create_time", err: errors.New(`ent: missing required field "PaymentIntent.create_time"`)}
	}
	if _, ok := pic.mutation.UpdateTime(); !ok {
		return &ValidationError{Name: "update_time", err: errors.New(`ent: missing required field "PaymentIntent.update_time"`)}
	}
	if _, ok := pic.mutation.PaymentIntent(); !ok {
		return &ValidationError{Name: "payment_intent", err: errors.New(`ent: missing required field "PaymentIntent.payment_intent"`)}
	}
	if v, ok := pic.mutation.PaymentIntent(); ok {
		if err := paymentintent.PaymentIntentValidator(v); err != nil {
			return &ValidationError{Name: "payment_intent", err: fmt.Errorf(`ent: validator failed for field "PaymentIntent.payment_intent": %w`, err)}
		}
	}
	return nil
}

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

func (pic *PaymentIntentCreate) createSpec() (*PaymentIntent, *sqlgraph.CreateSpec) {
	var (
		_node = &PaymentIntent{config: pic.config}
		_spec = sqlgraph.NewCreateSpec(paymentintent.Table, sqlgraph.NewFieldSpec(paymentintent.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = pic.conflict
	if id, ok := pic.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := pic.mutation.CreateTime(); ok {
		_spec.SetField(paymentintent.FieldCreateTime, field.TypeTime, value)
		_node.CreateTime = value
	}
	if value, ok := pic.mutation.UpdateTime(); ok {
		_spec.SetField(paymentintent.FieldUpdateTime, field.TypeTime, value)
		_node.UpdateTime = value
	}
	if value, ok := pic.mutation.PaymentIntent(); ok {
		_spec.SetField(paymentintent.FieldPaymentIntent, field.TypeString, value)
		_node.PaymentIntent = value
	}
	if nodes := pic.mutation.TransferIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: true,
			Table:   paymentintent.TransferTable,
			Columns: []string{paymentintent.TransferColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(transfer.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := pic.mutation.TokenTransactionIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: true,
			Table:   paymentintent.TokenTransactionTable,
			Columns: []string{paymentintent.TokenTransactionColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(tokentransaction.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.PaymentIntent.Create().
//		SetCreateTime(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.PaymentIntentUpsert) {
//			SetCreateTime(v+v).
//		}).
//		Exec(ctx)
func (pic *PaymentIntentCreate) OnConflict(opts ...sql.ConflictOption) *PaymentIntentUpsertOne {
	pic.conflict = opts
	return &PaymentIntentUpsertOne{
		create: pic,
	}
}

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

type (
	// PaymentIntentUpsertOne is the builder for "upsert"-ing
	//  one PaymentIntent node.
	PaymentIntentUpsertOne struct {
		create *PaymentIntentCreate
	}

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

// SetUpdateTime sets the "update_time" field.
func (u *PaymentIntentUpsert) SetUpdateTime(v time.Time) *PaymentIntentUpsert {
	u.Set(paymentintent.FieldUpdateTime, v)
	return u
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *PaymentIntentUpsert) UpdateUpdateTime() *PaymentIntentUpsert {
	u.SetExcluded(paymentintent.FieldUpdateTime)
	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.PaymentIntent.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(paymentintent.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *PaymentIntentUpsertOne) UpdateNewValues() *PaymentIntentUpsertOne {
	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(paymentintent.FieldID)
		}
		if _, exists := u.create.mutation.CreateTime(); exists {
			s.SetIgnore(paymentintent.FieldCreateTime)
		}
		if _, exists := u.create.mutation.PaymentIntent(); exists {
			s.SetIgnore(paymentintent.FieldPaymentIntent)
		}
	}))
	return u
}

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

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

// SetUpdateTime sets the "update_time" field.
func (u *PaymentIntentUpsertOne) SetUpdateTime(v time.Time) *PaymentIntentUpsertOne {
	return u.Update(func(s *PaymentIntentUpsert) {
		s.SetUpdateTime(v)
	})
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *PaymentIntentUpsertOne) UpdateUpdateTime() *PaymentIntentUpsertOne {
	return u.Update(func(s *PaymentIntentUpsert) {
		s.UpdateUpdateTime()
	})
}

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

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

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

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.PaymentIntent.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.PaymentIntentUpsert) {
//			SetCreateTime(v+v).
//		}).
//		Exec(ctx)
func (picb *PaymentIntentCreateBulk) OnConflict(opts ...sql.ConflictOption) *PaymentIntentUpsertBulk {
	picb.conflict = opts
	return &PaymentIntentUpsertBulk{
		create: picb,
	}
}

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

// PaymentIntentUpsertBulk is the builder for "upsert"-ing
// a bulk of PaymentIntent nodes.
type PaymentIntentUpsertBulk struct {
	create *PaymentIntentCreateBulk
}

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

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

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

// SetUpdateTime sets the "update_time" field.
func (u *PaymentIntentUpsertBulk) SetUpdateTime(v time.Time) *PaymentIntentUpsertBulk {
	return u.Update(func(s *PaymentIntentUpsert) {
		s.SetUpdateTime(v)
	})
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *PaymentIntentUpsertBulk) UpdateUpdateTime() *PaymentIntentUpsertBulk {
	return u.Update(func(s *PaymentIntentUpsert) {
		s.UpdateUpdateTime()
	})
}

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

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