// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"

	"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/groupuser"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/schema"
	entuser "github.com/lunabrain-ai/lunabrain/pkg/ent/user"
	"github.com/markbates/goth"
)

// UserCreate is the builder for creating a User entity.
type UserCreate struct {
	config
	mutation *UserMutation
	hooks    []Hook
}

// SetEmail sets the "email" field.
func (uc *UserCreate) SetEmail(s string) *UserCreate {
	uc.mutation.SetEmail(s)
	return uc
}

// SetPasswordHash sets the "password_hash" field.
func (uc *UserCreate) SetPasswordHash(s string) *UserCreate {
	uc.mutation.SetPasswordHash(s)
	return uc
}

// SetNillablePasswordHash sets the "password_hash" field if the given value is not nil.
func (uc *UserCreate) SetNillablePasswordHash(s *string) *UserCreate {
	if s != nil {
		uc.SetPasswordHash(*s)
	}
	return uc
}

// SetData sets the "data" field.
func (uc *UserCreate) SetData(se schema.UserEncoder) *UserCreate {
	uc.mutation.SetData(se)
	return uc
}

// SetVerified sets the "verified" field.
func (uc *UserCreate) SetVerified(b bool) *UserCreate {
	uc.mutation.SetVerified(b)
	return uc
}

// SetNillableVerified sets the "verified" field if the given value is not nil.
func (uc *UserCreate) SetNillableVerified(b *bool) *UserCreate {
	if b != nil {
		uc.SetVerified(*b)
	}
	return uc
}

// SetVerifySecret sets the "verify_secret" field.
func (uc *UserCreate) SetVerifySecret(u uuid.UUID) *UserCreate {
	uc.mutation.SetVerifySecret(u)
	return uc
}

// SetNillableVerifySecret sets the "verify_secret" field if the given value is not nil.
func (uc *UserCreate) SetNillableVerifySecret(u *uuid.UUID) *UserCreate {
	if u != nil {
		uc.SetVerifySecret(*u)
	}
	return uc
}

// SetOauthUser sets the "oauth_user" field.
func (uc *UserCreate) SetOauthUser(_go goth.User) *UserCreate {
	uc.mutation.SetOauthUser(_go)
	return uc
}

// SetNillableOauthUser sets the "oauth_user" field if the given value is not nil.
func (uc *UserCreate) SetNillableOauthUser(_go *goth.User) *UserCreate {
	if _go != nil {
		uc.SetOauthUser(*_go)
	}
	return uc
}

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

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

// AddContentIDs adds the "content" edge to the Content entity by IDs.
func (uc *UserCreate) AddContentIDs(ids ...uuid.UUID) *UserCreate {
	uc.mutation.AddContentIDs(ids...)
	return uc
}

// AddContent adds the "content" edges to the Content entity.
func (uc *UserCreate) AddContent(c ...*Content) *UserCreate {
	ids := make([]uuid.UUID, len(c))
	for i := range c {
		ids[i] = c[i].ID
	}
	return uc.AddContentIDs(ids...)
}

// AddGroupUserIDs adds the "group_users" edge to the GroupUser entity by IDs.
func (uc *UserCreate) AddGroupUserIDs(ids ...uuid.UUID) *UserCreate {
	uc.mutation.AddGroupUserIDs(ids...)
	return uc
}

// AddGroupUsers adds the "group_users" edges to the GroupUser entity.
func (uc *UserCreate) AddGroupUsers(g ...*GroupUser) *UserCreate {
	ids := make([]uuid.UUID, len(g))
	for i := range g {
		ids[i] = g[i].ID
	}
	return uc.AddGroupUserIDs(ids...)
}

// Mutation returns the UserMutation object of the builder.
func (uc *UserCreate) Mutation() *UserMutation {
	return uc.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (uc *UserCreate) defaults() {
	if _, ok := uc.mutation.Verified(); !ok {
		v := entuser.DefaultVerified
		uc.mutation.SetVerified(v)
	}
	if _, ok := uc.mutation.OauthUser(); !ok {
		v := entuser.DefaultOauthUser
		uc.mutation.SetOauthUser(v)
	}
	if _, ok := uc.mutation.ID(); !ok {
		v := entuser.DefaultID()
		uc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (uc *UserCreate) check() error {
	if _, ok := uc.mutation.Email(); !ok {
		return &ValidationError{Name: "email", err: errors.New(`ent: missing required field "User.email"`)}
	}
	if _, ok := uc.mutation.Data(); !ok {
		return &ValidationError{Name: "data", err: errors.New(`ent: missing required field "User.data"`)}
	}
	if _, ok := uc.mutation.Verified(); !ok {
		return &ValidationError{Name: "verified", err: errors.New(`ent: missing required field "User.verified"`)}
	}
	if _, ok := uc.mutation.OauthUser(); !ok {
		return &ValidationError{Name: "oauth_user", err: errors.New(`ent: missing required field "User.oauth_user"`)}
	}
	return nil
}

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

func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
	var (
		_node = &User{config: uc.config}
		_spec = sqlgraph.NewCreateSpec(entuser.Table, sqlgraph.NewFieldSpec(entuser.FieldID, field.TypeUUID))
	)
	if id, ok := uc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := uc.mutation.Email(); ok {
		_spec.SetField(entuser.FieldEmail, field.TypeString, value)
		_node.Email = value
	}
	if value, ok := uc.mutation.PasswordHash(); ok {
		_spec.SetField(entuser.FieldPasswordHash, field.TypeString, value)
		_node.PasswordHash = value
	}
	if value, ok := uc.mutation.Data(); ok {
		_spec.SetField(entuser.FieldData, field.TypeJSON, value)
		_node.Data = value
	}
	if value, ok := uc.mutation.Verified(); ok {
		_spec.SetField(entuser.FieldVerified, field.TypeBool, value)
		_node.Verified = value
	}
	if value, ok := uc.mutation.VerifySecret(); ok {
		_spec.SetField(entuser.FieldVerifySecret, field.TypeUUID, value)
		_node.VerifySecret = value
	}
	if value, ok := uc.mutation.OauthUser(); ok {
		_spec.SetField(entuser.FieldOauthUser, field.TypeJSON, value)
		_node.OauthUser = value
	}
	if nodes := uc.mutation.ContentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   entuser.ContentTable,
			Columns: []string{entuser.ContentColumn},
			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 := uc.mutation.GroupUsersIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   entuser.GroupUsersTable,
			Columns: []string{entuser.GroupUsersColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(groupuser.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
	config
	err      error
	builders []*UserCreate
}

// Save creates the User entities in the database.
func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
	if ucb.err != nil {
		return nil, ucb.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(ucb.builders))
	nodes := make([]*User, len(ucb.builders))
	mutators := make([]Mutator, len(ucb.builders))
	for i := range ucb.builders {
		func(i int, root context.Context) {
			builder := ucb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*UserMutation)
				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, ucb.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, ucb.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, ucb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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