// 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/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/attestation"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun"
	"github.com/google/uuid"
)

// AttestationCreate is the builder for creating a Attestation entity.
type AttestationCreate struct {
	config
	mutation *AttestationMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

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

// SetBundle sets the "bundle" field.
func (ac *AttestationCreate) SetBundle(b []byte) *AttestationCreate {
	ac.mutation.SetBundle(b)
	return ac
}

// SetWorkflowrunID sets the "workflowrun_id" field.
func (ac *AttestationCreate) SetWorkflowrunID(u uuid.UUID) *AttestationCreate {
	ac.mutation.SetWorkflowrunID(u)
	return ac
}

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

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

// SetWorkflowrun sets the "workflowrun" edge to the WorkflowRun entity.
func (ac *AttestationCreate) SetWorkflowrun(w *WorkflowRun) *AttestationCreate {
	return ac.SetWorkflowrunID(w.ID)
}

// Mutation returns the AttestationMutation object of the builder.
func (ac *AttestationCreate) Mutation() *AttestationMutation {
	return ac.mutation
}

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

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (ac *AttestationCreate) check() error {
	if _, ok := ac.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Attestation.created_at"`)}
	}
	if _, ok := ac.mutation.Bundle(); !ok {
		return &ValidationError{Name: "bundle", err: errors.New(`ent: missing required field "Attestation.bundle"`)}
	}
	if v, ok := ac.mutation.Bundle(); ok {
		if err := attestation.BundleValidator(v); err != nil {
			return &ValidationError{Name: "bundle", err: fmt.Errorf(`ent: validator failed for field "Attestation.bundle": %w`, err)}
		}
	}
	if _, ok := ac.mutation.WorkflowrunID(); !ok {
		return &ValidationError{Name: "workflowrun_id", err: errors.New(`ent: missing required field "Attestation.workflowrun_id"`)}
	}
	if len(ac.mutation.WorkflowrunIDs()) == 0 {
		return &ValidationError{Name: "workflowrun", err: errors.New(`ent: missing required edge "Attestation.workflowrun"`)}
	}
	return nil
}

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

func (ac *AttestationCreate) createSpec() (*Attestation, *sqlgraph.CreateSpec) {
	var (
		_node = &Attestation{config: ac.config}
		_spec = sqlgraph.NewCreateSpec(attestation.Table, sqlgraph.NewFieldSpec(attestation.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = ac.conflict
	if id, ok := ac.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := ac.mutation.CreatedAt(); ok {
		_spec.SetField(attestation.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := ac.mutation.Bundle(); ok {
		_spec.SetField(attestation.FieldBundle, field.TypeBytes, value)
		_node.Bundle = value
	}
	if nodes := ac.mutation.WorkflowrunIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2O,
			Inverse: true,
			Table:   attestation.WorkflowrunTable,
			Columns: []string{attestation.WorkflowrunColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(workflowrun.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.WorkflowrunID = 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.Attestation.Create().
//		SetCreatedAt(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.AttestationUpsert) {
//			SetCreatedAt(v+v).
//		}).
//		Exec(ctx)
func (ac *AttestationCreate) OnConflict(opts ...sql.ConflictOption) *AttestationUpsertOne {
	ac.conflict = opts
	return &AttestationUpsertOne{
		create: ac,
	}
}

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

type (
	// AttestationUpsertOne is the builder for "upsert"-ing
	//  one Attestation node.
	AttestationUpsertOne struct {
		create *AttestationCreate
	}

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

// 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.Attestation.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(attestation.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *AttestationUpsertOne) UpdateNewValues() *AttestationUpsertOne {
	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(attestation.FieldID)
		}
		if _, exists := u.create.mutation.CreatedAt(); exists {
			s.SetIgnore(attestation.FieldCreatedAt)
		}
		if _, exists := u.create.mutation.Bundle(); exists {
			s.SetIgnore(attestation.FieldBundle)
		}
		if _, exists := u.create.mutation.WorkflowrunID(); exists {
			s.SetIgnore(attestation.FieldWorkflowrunID)
		}
	}))
	return u
}

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

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

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

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

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

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Attestation.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.AttestationUpsert) {
//			SetCreatedAt(v+v).
//		}).
//		Exec(ctx)
func (acb *AttestationCreateBulk) OnConflict(opts ...sql.ConflictOption) *AttestationUpsertBulk {
	acb.conflict = opts
	return &AttestationUpsertBulk{
		create: acb,
	}
}

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

// AttestationUpsertBulk is the builder for "upsert"-ing
// a bulk of Attestation nodes.
type AttestationUpsertBulk struct {
	create *AttestationCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.Attestation.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(attestation.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *AttestationUpsertBulk) UpdateNewValues() *AttestationUpsertBulk {
	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(attestation.FieldID)
			}
			if _, exists := b.mutation.CreatedAt(); exists {
				s.SetIgnore(attestation.FieldCreatedAt)
			}
			if _, exists := b.mutation.Bundle(); exists {
				s.SetIgnore(attestation.FieldBundle)
			}
			if _, exists := b.mutation.WorkflowrunID(); exists {
				s.SetIgnore(attestation.FieldWorkflowrunID)
			}
		}
	}))
	return u
}

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

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

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

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