// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/content"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/group"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/schema"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/tag"
	entuser "github.com/lunabrain-ai/lunabrain/pkg/ent/user"
)

// ContentCreate is the builder for creating a Content entity.
type ContentCreate struct {
	config
	mutation *ContentMutation
	hooks    []Hook
}

// SetRoot sets the "root" field.
func (cc *ContentCreate) SetRoot(b bool) *ContentCreate {
	cc.mutation.SetRoot(b)
	return cc
}

// SetData sets the "data" field.
func (cc *ContentCreate) SetData(se *schema.ContentEncoder) *ContentCreate {
	cc.mutation.SetData(se)
	return cc
}

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

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

// SetUpdatedAt sets the "updated_at" field.
func (cc *ContentCreate) SetUpdatedAt(t time.Time) *ContentCreate {
	cc.mutation.SetUpdatedAt(t)
	return cc
}

// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (cc *ContentCreate) SetNillableUpdatedAt(t *time.Time) *ContentCreate {
	if t != nil {
		cc.SetUpdatedAt(*t)
	}
	return cc
}

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

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

// SetUserID sets the "user" edge to the User entity by ID.
func (cc *ContentCreate) SetUserID(id uuid.UUID) *ContentCreate {
	cc.mutation.SetUserID(id)
	return cc
}

// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (cc *ContentCreate) SetNillableUserID(id *uuid.UUID) *ContentCreate {
	if id != nil {
		cc = cc.SetUserID(*id)
	}
	return cc
}

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

// AddTagIDs adds the "tags" edge to the Tag entity by IDs.
func (cc *ContentCreate) AddTagIDs(ids ...uuid.UUID) *ContentCreate {
	cc.mutation.AddTagIDs(ids...)
	return cc
}

// AddTags adds the "tags" edges to the Tag entity.
func (cc *ContentCreate) AddTags(t ...*Tag) *ContentCreate {
	ids := make([]uuid.UUID, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return cc.AddTagIDs(ids...)
}

// AddChildIDs adds the "children" edge to the Content entity by IDs.
func (cc *ContentCreate) AddChildIDs(ids ...uuid.UUID) *ContentCreate {
	cc.mutation.AddChildIDs(ids...)
	return cc
}

// AddChildren adds the "children" edges to the Content entity.
func (cc *ContentCreate) AddChildren(c ...*Content) *ContentCreate {
	ids := make([]uuid.UUID, len(c))
	for i := range c {
		ids[i] = c[i].ID
	}
	return cc.AddChildIDs(ids...)
}

// AddParentIDs adds the "parents" edge to the Content entity by IDs.
func (cc *ContentCreate) AddParentIDs(ids ...uuid.UUID) *ContentCreate {
	cc.mutation.AddParentIDs(ids...)
	return cc
}

// AddParents adds the "parents" edges to the Content entity.
func (cc *ContentCreate) AddParents(c ...*Content) *ContentCreate {
	ids := make([]uuid.UUID, len(c))
	for i := range c {
		ids[i] = c[i].ID
	}
	return cc.AddParentIDs(ids...)
}

// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (cc *ContentCreate) AddGroupIDs(ids ...uuid.UUID) *ContentCreate {
	cc.mutation.AddGroupIDs(ids...)
	return cc
}

// AddGroups adds the "groups" edges to the Group entity.
func (cc *ContentCreate) AddGroups(g ...*Group) *ContentCreate {
	ids := make([]uuid.UUID, len(g))
	for i := range g {
		ids[i] = g[i].ID
	}
	return cc.AddGroupIDs(ids...)
}

// Mutation returns the ContentMutation object of the builder.
func (cc *ContentCreate) Mutation() *ContentMutation {
	return cc.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (cc *ContentCreate) defaults() {
	if _, ok := cc.mutation.CreatedAt(); !ok {
		v := content.DefaultCreatedAt()
		cc.mutation.SetCreatedAt(v)
	}
	if _, ok := cc.mutation.UpdatedAt(); !ok {
		v := content.DefaultUpdatedAt()
		cc.mutation.SetUpdatedAt(v)
	}
	if _, ok := cc.mutation.ID(); !ok {
		v := content.DefaultID()
		cc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (cc *ContentCreate) check() error {
	if _, ok := cc.mutation.Root(); !ok {
		return &ValidationError{Name: "root", err: errors.New(`ent: missing required field "Content.root"`)}
	}
	if _, ok := cc.mutation.Data(); !ok {
		return &ValidationError{Name: "data", err: errors.New(`ent: missing required field "Content.data"`)}
	}
	if _, ok := cc.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Content.created_at"`)}
	}
	return nil
}

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

func (cc *ContentCreate) createSpec() (*Content, *sqlgraph.CreateSpec) {
	var (
		_node = &Content{config: cc.config}
		_spec = sqlgraph.NewCreateSpec(content.Table, sqlgraph.NewFieldSpec(content.FieldID, field.TypeUUID))
	)
	if id, ok := cc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := cc.mutation.Root(); ok {
		_spec.SetField(content.FieldRoot, field.TypeBool, value)
		_node.Root = value
	}
	if value, ok := cc.mutation.Data(); ok {
		_spec.SetField(content.FieldData, field.TypeJSON, value)
		_node.Data = value
	}
	if value, ok := cc.mutation.CreatedAt(); ok {
		_spec.SetField(content.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := cc.mutation.UpdatedAt(); ok {
		_spec.SetField(content.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if nodes := cc.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   content.UserTable,
			Columns: []string{content.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(entuser.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.user_content = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := cc.mutation.TagsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   content.TagsTable,
			Columns: content.TagsPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := cc.mutation.ChildrenIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: false,
			Table:   content.ChildrenTable,
			Columns: content.ChildrenPrimaryKey,
			Bidi:    true,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(content.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := cc.mutation.ParentsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   content.ParentsTable,
			Columns: content.ParentsPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(content.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := cc.mutation.GroupsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: false,
			Table:   content.GroupsTable,
			Columns: content.GroupsPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// ContentCreateBulk is the builder for creating many Content entities in bulk.
type ContentCreateBulk struct {
	config
	err      error
	builders []*ContentCreate
}

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

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

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

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