// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.

// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/entc/integration/edgeschema/ent/tweet"
	"entgo.io/ent/entc/integration/edgeschema/ent/tweetlike"
	"entgo.io/ent/entc/integration/edgeschema/ent/user"
	"entgo.io/ent/schema/field"
)

// TweetLikeCreate is the builder for creating a TweetLike entity.
type TweetLikeCreate struct {
	config
	mutation *TweetLikeMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetLikedAt sets the "liked_at" field.
func (tlc *TweetLikeCreate) SetLikedAt(t time.Time) *TweetLikeCreate {
	tlc.mutation.SetLikedAt(t)
	return tlc
}

// SetNillableLikedAt sets the "liked_at" field if the given value is not nil.
func (tlc *TweetLikeCreate) SetNillableLikedAt(t *time.Time) *TweetLikeCreate {
	if t != nil {
		tlc.SetLikedAt(*t)
	}
	return tlc
}

// SetUserID sets the "user_id" field.
func (tlc *TweetLikeCreate) SetUserID(i int) *TweetLikeCreate {
	tlc.mutation.SetUserID(i)
	return tlc
}

// SetTweetID sets the "tweet_id" field.
func (tlc *TweetLikeCreate) SetTweetID(i int) *TweetLikeCreate {
	tlc.mutation.SetTweetID(i)
	return tlc
}

// SetTweet sets the "tweet" edge to the Tweet entity.
func (tlc *TweetLikeCreate) SetTweet(t *Tweet) *TweetLikeCreate {
	return tlc.SetTweetID(t.ID)
}

// SetUser sets the "user" edge to the User entity.
func (tlc *TweetLikeCreate) SetUser(u *User) *TweetLikeCreate {
	return tlc.SetUserID(u.ID)
}

// Mutation returns the TweetLikeMutation object of the builder.
func (tlc *TweetLikeCreate) Mutation() *TweetLikeMutation {
	return tlc.mutation
}

// Save creates the TweetLike in the database.
func (tlc *TweetLikeCreate) Save(ctx context.Context) (*TweetLike, error) {
	if err := tlc.defaults(); err != nil {
		return nil, err
	}
	return withHooks[*TweetLike, TweetLikeMutation](ctx, tlc.sqlSave, tlc.mutation, tlc.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (tlc *TweetLikeCreate) defaults() error {
	if _, ok := tlc.mutation.LikedAt(); !ok {
		if tweetlike.DefaultLikedAt == nil {
			return fmt.Errorf("ent: uninitialized tweetlike.DefaultLikedAt (forgotten import ent/runtime?)")
		}
		v := tweetlike.DefaultLikedAt()
		tlc.mutation.SetLikedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (tlc *TweetLikeCreate) check() error {
	if _, ok := tlc.mutation.LikedAt(); !ok {
		return &ValidationError{Name: "liked_at", err: errors.New(`ent: missing required field "TweetLike.liked_at"`)}
	}
	if _, ok := tlc.mutation.UserID(); !ok {
		return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "TweetLike.user_id"`)}
	}
	if _, ok := tlc.mutation.TweetID(); !ok {
		return &ValidationError{Name: "tweet_id", err: errors.New(`ent: missing required field "TweetLike.tweet_id"`)}
	}
	if _, ok := tlc.mutation.TweetID(); !ok {
		return &ValidationError{Name: "tweet", err: errors.New(`ent: missing required edge "TweetLike.tweet"`)}
	}
	if _, ok := tlc.mutation.UserID(); !ok {
		return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "TweetLike.user"`)}
	}
	return nil
}

func (tlc *TweetLikeCreate) sqlSave(ctx context.Context) (*TweetLike, error) {
	if err := tlc.check(); err != nil {
		return nil, err
	}
	_node, _spec := tlc.createSpec()
	if err := sqlgraph.CreateNode(ctx, tlc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	return _node, nil
}

func (tlc *TweetLikeCreate) createSpec() (*TweetLike, *sqlgraph.CreateSpec) {
	var (
		_node = &TweetLike{config: tlc.config}
		_spec = sqlgraph.NewCreateSpec(tweetlike.Table, nil)
	)
	_spec.OnConflict = tlc.conflict
	if value, ok := tlc.mutation.LikedAt(); ok {
		_spec.SetField(tweetlike.FieldLikedAt, field.TypeTime, value)
		_node.LikedAt = value
	}
	if nodes := tlc.mutation.TweetIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   tweetlike.TweetTable,
			Columns: []string{tweetlike.TweetColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(tweet.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.TweetID = nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := tlc.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   tweetlike.UserTable,
			Columns: []string{tweetlike.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.UserID = nodes[0]
		_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.TweetLike.Create().
//		SetLikedAt(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.TweetLikeUpsert) {
//			SetLikedAt(v+v).
//		}).
//		Exec(ctx)
func (tlc *TweetLikeCreate) OnConflict(opts ...sql.ConflictOption) *TweetLikeUpsertOne {
	tlc.conflict = opts
	return &TweetLikeUpsertOne{
		create: tlc,
	}
}

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

type (
	// TweetLikeUpsertOne is the builder for "upsert"-ing
	//  one TweetLike node.
	TweetLikeUpsertOne struct {
		create *TweetLikeCreate
	}

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

// SetLikedAt sets the "liked_at" field.
func (u *TweetLikeUpsert) SetLikedAt(v time.Time) *TweetLikeUpsert {
	u.Set(tweetlike.FieldLikedAt, v)
	return u
}

// UpdateLikedAt sets the "liked_at" field to the value that was provided on create.
func (u *TweetLikeUpsert) UpdateLikedAt() *TweetLikeUpsert {
	u.SetExcluded(tweetlike.FieldLikedAt)
	return u
}

// SetUserID sets the "user_id" field.
func (u *TweetLikeUpsert) SetUserID(v int) *TweetLikeUpsert {
	u.Set(tweetlike.FieldUserID, v)
	return u
}

// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *TweetLikeUpsert) UpdateUserID() *TweetLikeUpsert {
	u.SetExcluded(tweetlike.FieldUserID)
	return u
}

// SetTweetID sets the "tweet_id" field.
func (u *TweetLikeUpsert) SetTweetID(v int) *TweetLikeUpsert {
	u.Set(tweetlike.FieldTweetID, v)
	return u
}

// UpdateTweetID sets the "tweet_id" field to the value that was provided on create.
func (u *TweetLikeUpsert) UpdateTweetID() *TweetLikeUpsert {
	u.SetExcluded(tweetlike.FieldTweetID)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
//	client.TweetLike.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *TweetLikeUpsertOne) UpdateNewValues() *TweetLikeUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	return u
}

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

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

// SetLikedAt sets the "liked_at" field.
func (u *TweetLikeUpsertOne) SetLikedAt(v time.Time) *TweetLikeUpsertOne {
	return u.Update(func(s *TweetLikeUpsert) {
		s.SetLikedAt(v)
	})
}

// UpdateLikedAt sets the "liked_at" field to the value that was provided on create.
func (u *TweetLikeUpsertOne) UpdateLikedAt() *TweetLikeUpsertOne {
	return u.Update(func(s *TweetLikeUpsert) {
		s.UpdateLikedAt()
	})
}

// SetUserID sets the "user_id" field.
func (u *TweetLikeUpsertOne) SetUserID(v int) *TweetLikeUpsertOne {
	return u.Update(func(s *TweetLikeUpsert) {
		s.SetUserID(v)
	})
}

// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *TweetLikeUpsertOne) UpdateUserID() *TweetLikeUpsertOne {
	return u.Update(func(s *TweetLikeUpsert) {
		s.UpdateUserID()
	})
}

// SetTweetID sets the "tweet_id" field.
func (u *TweetLikeUpsertOne) SetTweetID(v int) *TweetLikeUpsertOne {
	return u.Update(func(s *TweetLikeUpsert) {
		s.SetTweetID(v)
	})
}

// UpdateTweetID sets the "tweet_id" field to the value that was provided on create.
func (u *TweetLikeUpsertOne) UpdateTweetID() *TweetLikeUpsertOne {
	return u.Update(func(s *TweetLikeUpsert) {
		s.UpdateTweetID()
	})
}

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

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

// TweetLikeCreateBulk is the builder for creating many TweetLike entities in bulk.
type TweetLikeCreateBulk struct {
	config
	builders []*TweetLikeCreate
	conflict []sql.ConflictOption
}

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.TweetLike.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.TweetLikeUpsert) {
//			SetLikedAt(v+v).
//		}).
//		Exec(ctx)
func (tlcb *TweetLikeCreateBulk) OnConflict(opts ...sql.ConflictOption) *TweetLikeUpsertBulk {
	tlcb.conflict = opts
	return &TweetLikeUpsertBulk{
		create: tlcb,
	}
}

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

// TweetLikeUpsertBulk is the builder for "upsert"-ing
// a bulk of TweetLike nodes.
type TweetLikeUpsertBulk struct {
	create *TweetLikeCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.TweetLike.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *TweetLikeUpsertBulk) UpdateNewValues() *TweetLikeUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	return u
}

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

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

// SetLikedAt sets the "liked_at" field.
func (u *TweetLikeUpsertBulk) SetLikedAt(v time.Time) *TweetLikeUpsertBulk {
	return u.Update(func(s *TweetLikeUpsert) {
		s.SetLikedAt(v)
	})
}

// UpdateLikedAt sets the "liked_at" field to the value that was provided on create.
func (u *TweetLikeUpsertBulk) UpdateLikedAt() *TweetLikeUpsertBulk {
	return u.Update(func(s *TweetLikeUpsert) {
		s.UpdateLikedAt()
	})
}

// SetUserID sets the "user_id" field.
func (u *TweetLikeUpsertBulk) SetUserID(v int) *TweetLikeUpsertBulk {
	return u.Update(func(s *TweetLikeUpsert) {
		s.SetUserID(v)
	})
}

// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *TweetLikeUpsertBulk) UpdateUserID() *TweetLikeUpsertBulk {
	return u.Update(func(s *TweetLikeUpsert) {
		s.UpdateUserID()
	})
}

// SetTweetID sets the "tweet_id" field.
func (u *TweetLikeUpsertBulk) SetTweetID(v int) *TweetLikeUpsertBulk {
	return u.Update(func(s *TweetLikeUpsert) {
		s.SetTweetID(v)
	})
}

// UpdateTweetID sets the "tweet_id" field to the value that was provided on create.
func (u *TweetLikeUpsertBulk) UpdateTweetID() *TweetLikeUpsertBulk {
	return u.Update(func(s *TweetLikeUpsert) {
		s.UpdateTweetID()
	})
}

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

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