// 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/schema/field"
	"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
)

// MetricCreate is the builder for creating a Metric entity.
type MetricCreate struct {
	config
	mutation *MetricMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetGeneratedType sets the "generated_type" field.
func (mc *MetricCreate) SetGeneratedType(mt metric.GeneratedType) *MetricCreate {
	mc.mutation.SetGeneratedType(mt)
	return mc
}

// SetGeneratedBy sets the "generated_by" field.
func (mc *MetricCreate) SetGeneratedBy(s string) *MetricCreate {
	mc.mutation.SetGeneratedBy(s)
	return mc
}

// SetReceivedAt sets the "received_at" field.
func (mc *MetricCreate) SetReceivedAt(t time.Time) *MetricCreate {
	mc.mutation.SetReceivedAt(t)
	return mc
}

// SetPushedAt sets the "pushed_at" field.
func (mc *MetricCreate) SetPushedAt(t time.Time) *MetricCreate {
	mc.mutation.SetPushedAt(t)
	return mc
}

// SetNillablePushedAt sets the "pushed_at" field if the given value is not nil.
func (mc *MetricCreate) SetNillablePushedAt(t *time.Time) *MetricCreate {
	if t != nil {
		mc.SetPushedAt(*t)
	}
	return mc
}

// SetPayload sets the "payload" field.
func (mc *MetricCreate) SetPayload(s string) *MetricCreate {
	mc.mutation.SetPayload(s)
	return mc
}

// Mutation returns the MetricMutation object of the builder.
func (mc *MetricCreate) Mutation() *MetricMutation {
	return mc.mutation
}

// Save creates the Metric in the database.
func (mc *MetricCreate) Save(ctx context.Context) (*Metric, error) {
	return withHooks(ctx, mc.sqlSave, mc.mutation, mc.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (mc *MetricCreate) check() error {
	if _, ok := mc.mutation.GeneratedType(); !ok {
		return &ValidationError{Name: "generated_type", err: errors.New(`ent: missing required field "Metric.generated_type"`)}
	}
	if v, ok := mc.mutation.GeneratedType(); ok {
		if err := metric.GeneratedTypeValidator(v); err != nil {
			return &ValidationError{Name: "generated_type", err: fmt.Errorf(`ent: validator failed for field "Metric.generated_type": %w`, err)}
		}
	}
	if _, ok := mc.mutation.GeneratedBy(); !ok {
		return &ValidationError{Name: "generated_by", err: errors.New(`ent: missing required field "Metric.generated_by"`)}
	}
	if _, ok := mc.mutation.ReceivedAt(); !ok {
		return &ValidationError{Name: "received_at", err: errors.New(`ent: missing required field "Metric.received_at"`)}
	}
	if _, ok := mc.mutation.Payload(); !ok {
		return &ValidationError{Name: "payload", err: errors.New(`ent: missing required field "Metric.payload"`)}
	}
	return nil
}

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

func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) {
	var (
		_node = &Metric{config: mc.config}
		_spec = sqlgraph.NewCreateSpec(metric.Table, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt))
	)
	_spec.OnConflict = mc.conflict
	if value, ok := mc.mutation.GeneratedType(); ok {
		_spec.SetField(metric.FieldGeneratedType, field.TypeEnum, value)
		_node.GeneratedType = value
	}
	if value, ok := mc.mutation.GeneratedBy(); ok {
		_spec.SetField(metric.FieldGeneratedBy, field.TypeString, value)
		_node.GeneratedBy = value
	}
	if value, ok := mc.mutation.ReceivedAt(); ok {
		_spec.SetField(metric.FieldReceivedAt, field.TypeTime, value)
		_node.ReceivedAt = value
	}
	if value, ok := mc.mutation.PushedAt(); ok {
		_spec.SetField(metric.FieldPushedAt, field.TypeTime, value)
		_node.PushedAt = &value
	}
	if value, ok := mc.mutation.Payload(); ok {
		_spec.SetField(metric.FieldPayload, field.TypeString, value)
		_node.Payload = value
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Metric.Create().
//		SetGeneratedType(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.MetricUpsert) {
//			SetGeneratedType(v+v).
//		}).
//		Exec(ctx)
func (mc *MetricCreate) OnConflict(opts ...sql.ConflictOption) *MetricUpsertOne {
	mc.conflict = opts
	return &MetricUpsertOne{
		create: mc,
	}
}

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

type (
	// MetricUpsertOne is the builder for "upsert"-ing
	//  one Metric node.
	MetricUpsertOne struct {
		create *MetricCreate
	}

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

// SetPushedAt sets the "pushed_at" field.
func (u *MetricUpsert) SetPushedAt(v time.Time) *MetricUpsert {
	u.Set(metric.FieldPushedAt, v)
	return u
}

// UpdatePushedAt sets the "pushed_at" field to the value that was provided on create.
func (u *MetricUpsert) UpdatePushedAt() *MetricUpsert {
	u.SetExcluded(metric.FieldPushedAt)
	return u
}

// ClearPushedAt clears the value of the "pushed_at" field.
func (u *MetricUpsert) ClearPushedAt() *MetricUpsert {
	u.SetNull(metric.FieldPushedAt)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
//	client.Metric.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *MetricUpsertOne) UpdateNewValues() *MetricUpsertOne {
	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.GeneratedType(); exists {
			s.SetIgnore(metric.FieldGeneratedType)
		}
		if _, exists := u.create.mutation.GeneratedBy(); exists {
			s.SetIgnore(metric.FieldGeneratedBy)
		}
		if _, exists := u.create.mutation.ReceivedAt(); exists {
			s.SetIgnore(metric.FieldReceivedAt)
		}
		if _, exists := u.create.mutation.Payload(); exists {
			s.SetIgnore(metric.FieldPayload)
		}
	}))
	return u
}

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

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

// SetPushedAt sets the "pushed_at" field.
func (u *MetricUpsertOne) SetPushedAt(v time.Time) *MetricUpsertOne {
	return u.Update(func(s *MetricUpsert) {
		s.SetPushedAt(v)
	})
}

// UpdatePushedAt sets the "pushed_at" field to the value that was provided on create.
func (u *MetricUpsertOne) UpdatePushedAt() *MetricUpsertOne {
	return u.Update(func(s *MetricUpsert) {
		s.UpdatePushedAt()
	})
}

// ClearPushedAt clears the value of the "pushed_at" field.
func (u *MetricUpsertOne) ClearPushedAt() *MetricUpsertOne {
	return u.Update(func(s *MetricUpsert) {
		s.ClearPushedAt()
	})
}

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

// ExecX is like Exec, but panics if an error occurs.
func (u *MetricUpsertOne) 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 *MetricUpsertOne) ID(ctx context.Context) (id int, err error) {
	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 *MetricUpsertOne) IDX(ctx context.Context) int {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

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

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Metric.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.MetricUpsert) {
//			SetGeneratedType(v+v).
//		}).
//		Exec(ctx)
func (mcb *MetricCreateBulk) OnConflict(opts ...sql.ConflictOption) *MetricUpsertBulk {
	mcb.conflict = opts
	return &MetricUpsertBulk{
		create: mcb,
	}
}

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

// MetricUpsertBulk is the builder for "upsert"-ing
// a bulk of Metric nodes.
type MetricUpsertBulk struct {
	create *MetricCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.Metric.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *MetricUpsertBulk) UpdateNewValues() *MetricUpsertBulk {
	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.GeneratedType(); exists {
				s.SetIgnore(metric.FieldGeneratedType)
			}
			if _, exists := b.mutation.GeneratedBy(); exists {
				s.SetIgnore(metric.FieldGeneratedBy)
			}
			if _, exists := b.mutation.ReceivedAt(); exists {
				s.SetIgnore(metric.FieldReceivedAt)
			}
			if _, exists := b.mutation.Payload(); exists {
				s.SetIgnore(metric.FieldPayload)
			}
		}
	}))
	return u
}

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

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

// SetPushedAt sets the "pushed_at" field.
func (u *MetricUpsertBulk) SetPushedAt(v time.Time) *MetricUpsertBulk {
	return u.Update(func(s *MetricUpsert) {
		s.SetPushedAt(v)
	})
}

// UpdatePushedAt sets the "pushed_at" field to the value that was provided on create.
func (u *MetricUpsertBulk) UpdatePushedAt() *MetricUpsertBulk {
	return u.Update(func(s *MetricUpsert) {
		s.UpdatePushedAt()
	})
}

// ClearPushedAt clears the value of the "pushed_at" field.
func (u *MetricUpsertBulk) ClearPushedAt() *MetricUpsertBulk {
	return u.Update(func(s *MetricUpsert) {
		s.ClearPushedAt()
	})
}

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

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