// 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/gossip"
	"github.com/lightsparkdev/spark/so/ent/schema/schematype"
)

// GossipCreate is the builder for creating a Gossip entity.
type GossipCreate struct {
	config
	mutation *GossipMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

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

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

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

// SetParticipants sets the "participants" field.
func (gc *GossipCreate) SetParticipants(s []string) *GossipCreate {
	gc.mutation.SetParticipants(s)
	return gc
}

// SetMessage sets the "message" field.
func (gc *GossipCreate) SetMessage(b []byte) *GossipCreate {
	gc.mutation.SetMessage(b)
	return gc
}

// SetReceipts sets the "receipts" field.
func (gc *GossipCreate) SetReceipts(b []byte) *GossipCreate {
	gc.mutation.SetReceipts(b)
	return gc
}

// SetStatus sets the "status" field.
func (gc *GossipCreate) SetStatus(ss schematype.GossipStatus) *GossipCreate {
	gc.mutation.SetStatus(ss)
	return gc
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (gc *GossipCreate) SetNillableStatus(ss *schematype.GossipStatus) *GossipCreate {
	if ss != nil {
		gc.SetStatus(*ss)
	}
	return gc
}

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

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

// Mutation returns the GossipMutation object of the builder.
func (gc *GossipCreate) Mutation() *GossipMutation {
	return gc.mutation
}

// Save creates the Gossip in the database.
func (gc *GossipCreate) Save(ctx context.Context) (*Gossip, error) {
	gc.defaults()
	return withHooks(ctx, gc.sqlSave, gc.mutation, gc.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (gc *GossipCreate) defaults() {
	if _, ok := gc.mutation.CreateTime(); !ok {
		v := gossip.DefaultCreateTime()
		gc.mutation.SetCreateTime(v)
	}
	if _, ok := gc.mutation.UpdateTime(); !ok {
		v := gossip.DefaultUpdateTime()
		gc.mutation.SetUpdateTime(v)
	}
	if _, ok := gc.mutation.Status(); !ok {
		v := gossip.DefaultStatus
		gc.mutation.SetStatus(v)
	}
	if _, ok := gc.mutation.ID(); !ok {
		v := gossip.DefaultID()
		gc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (gc *GossipCreate) check() error {
	if _, ok := gc.mutation.CreateTime(); !ok {
		return &ValidationError{Name: "create_time", err: errors.New(`ent: missing required field "Gossip.create_time"`)}
	}
	if _, ok := gc.mutation.UpdateTime(); !ok {
		return &ValidationError{Name: "update_time", err: errors.New(`ent: missing required field "Gossip.update_time"`)}
	}
	if _, ok := gc.mutation.Participants(); !ok {
		return &ValidationError{Name: "participants", err: errors.New(`ent: missing required field "Gossip.participants"`)}
	}
	if _, ok := gc.mutation.Message(); !ok {
		return &ValidationError{Name: "message", err: errors.New(`ent: missing required field "Gossip.message"`)}
	}
	if v, ok := gc.mutation.Message(); ok {
		if err := gossip.MessageValidator(v); err != nil {
			return &ValidationError{Name: "message", err: fmt.Errorf(`ent: validator failed for field "Gossip.message": %w`, err)}
		}
	}
	if _, ok := gc.mutation.Receipts(); !ok {
		return &ValidationError{Name: "receipts", err: errors.New(`ent: missing required field "Gossip.receipts"`)}
	}
	if _, ok := gc.mutation.Status(); !ok {
		return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Gossip.status"`)}
	}
	if v, ok := gc.mutation.Status(); ok {
		if err := gossip.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Gossip.status": %w`, err)}
		}
	}
	return nil
}

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

func (gc *GossipCreate) createSpec() (*Gossip, *sqlgraph.CreateSpec) {
	var (
		_node = &Gossip{config: gc.config}
		_spec = sqlgraph.NewCreateSpec(gossip.Table, sqlgraph.NewFieldSpec(gossip.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = gc.conflict
	if id, ok := gc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := gc.mutation.CreateTime(); ok {
		_spec.SetField(gossip.FieldCreateTime, field.TypeTime, value)
		_node.CreateTime = value
	}
	if value, ok := gc.mutation.UpdateTime(); ok {
		_spec.SetField(gossip.FieldUpdateTime, field.TypeTime, value)
		_node.UpdateTime = value
	}
	if value, ok := gc.mutation.Participants(); ok {
		_spec.SetField(gossip.FieldParticipants, field.TypeJSON, value)
		_node.Participants = value
	}
	if value, ok := gc.mutation.Message(); ok {
		_spec.SetField(gossip.FieldMessage, field.TypeBytes, value)
		_node.Message = value
	}
	if value, ok := gc.mutation.Receipts(); ok {
		_spec.SetField(gossip.FieldReceipts, field.TypeBytes, value)
		_node.Receipts = &value
	}
	if value, ok := gc.mutation.Status(); ok {
		_spec.SetField(gossip.FieldStatus, field.TypeEnum, value)
		_node.Status = value
	}
	return _node, _spec
}

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

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

type (
	// GossipUpsertOne is the builder for "upsert"-ing
	//  one Gossip node.
	GossipUpsertOne struct {
		create *GossipCreate
	}

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

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

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *GossipUpsert) UpdateUpdateTime() *GossipUpsert {
	u.SetExcluded(gossip.FieldUpdateTime)
	return u
}

// SetReceipts sets the "receipts" field.
func (u *GossipUpsert) SetReceipts(v []byte) *GossipUpsert {
	u.Set(gossip.FieldReceipts, v)
	return u
}

// UpdateReceipts sets the "receipts" field to the value that was provided on create.
func (u *GossipUpsert) UpdateReceipts() *GossipUpsert {
	u.SetExcluded(gossip.FieldReceipts)
	return u
}

// SetStatus sets the "status" field.
func (u *GossipUpsert) SetStatus(v schematype.GossipStatus) *GossipUpsert {
	u.Set(gossip.FieldStatus, v)
	return u
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *GossipUpsert) UpdateStatus() *GossipUpsert {
	u.SetExcluded(gossip.FieldStatus)
	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.Gossip.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(gossip.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *GossipUpsertOne) UpdateNewValues() *GossipUpsertOne {
	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(gossip.FieldID)
		}
		if _, exists := u.create.mutation.CreateTime(); exists {
			s.SetIgnore(gossip.FieldCreateTime)
		}
		if _, exists := u.create.mutation.Participants(); exists {
			s.SetIgnore(gossip.FieldParticipants)
		}
		if _, exists := u.create.mutation.Message(); exists {
			s.SetIgnore(gossip.FieldMessage)
		}
	}))
	return u
}

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

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

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

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

// SetReceipts sets the "receipts" field.
func (u *GossipUpsertOne) SetReceipts(v []byte) *GossipUpsertOne {
	return u.Update(func(s *GossipUpsert) {
		s.SetReceipts(v)
	})
}

// UpdateReceipts sets the "receipts" field to the value that was provided on create.
func (u *GossipUpsertOne) UpdateReceipts() *GossipUpsertOne {
	return u.Update(func(s *GossipUpsert) {
		s.UpdateReceipts()
	})
}

// SetStatus sets the "status" field.
func (u *GossipUpsertOne) SetStatus(v schematype.GossipStatus) *GossipUpsertOne {
	return u.Update(func(s *GossipUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *GossipUpsertOne) UpdateStatus() *GossipUpsertOne {
	return u.Update(func(s *GossipUpsert) {
		s.UpdateStatus()
	})
}

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

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

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

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

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

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

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

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

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

// GossipUpsertBulk is the builder for "upsert"-ing
// a bulk of Gossip nodes.
type GossipUpsertBulk struct {
	create *GossipCreateBulk
}

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

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

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

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

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

// SetReceipts sets the "receipts" field.
func (u *GossipUpsertBulk) SetReceipts(v []byte) *GossipUpsertBulk {
	return u.Update(func(s *GossipUpsert) {
		s.SetReceipts(v)
	})
}

// UpdateReceipts sets the "receipts" field to the value that was provided on create.
func (u *GossipUpsertBulk) UpdateReceipts() *GossipUpsertBulk {
	return u.Update(func(s *GossipUpsert) {
		s.UpdateReceipts()
	})
}

// SetStatus sets the "status" field.
func (u *GossipUpsertBulk) SetStatus(v schematype.GossipStatus) *GossipUpsertBulk {
	return u.Update(func(s *GossipUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *GossipUpsertBulk) UpdateStatus() *GossipUpsertBulk {
	return u.Update(func(s *GossipUpsert) {
		s.UpdateStatus()
	})
}

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

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