//go:build linux && cgo && !agent

package cluster

// The code below was generated by lxd-generate - DO NOT EDIT!

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"net/http"
	"strings"

	"github.com/canonical/lxd/lxd/db/query"
	"github.com/canonical/lxd/shared/api"
)

var _ = api.ServerEnvironment{}

var identityProviderGroupObjects = RegisterStmt(`
SELECT identity_provider_groups.id, identity_provider_groups.name
  FROM identity_provider_groups
  ORDER BY identity_provider_groups.name
`)

var identityProviderGroupObjectsByID = RegisterStmt(`
SELECT identity_provider_groups.id, identity_provider_groups.name
  FROM identity_provider_groups
  WHERE ( identity_provider_groups.id = ? )
  ORDER BY identity_provider_groups.name
`)

var identityProviderGroupObjectsByName = RegisterStmt(`
SELECT identity_provider_groups.id, identity_provider_groups.name
  FROM identity_provider_groups
  WHERE ( identity_provider_groups.name = ? )
  ORDER BY identity_provider_groups.name
`)

var identityProviderGroupID = RegisterStmt(`
SELECT identity_provider_groups.id FROM identity_provider_groups
  WHERE identity_provider_groups.name = ?
`)

var identityProviderGroupCreate = RegisterStmt(`
INSERT INTO identity_provider_groups (name)
  VALUES (?)
`)

var identityProviderGroupDeleteByName = RegisterStmt(`
DELETE FROM identity_provider_groups WHERE name = ?
`)

var identityProviderGroupUpdate = RegisterStmt(`
UPDATE identity_provider_groups
  SET name = ?
 WHERE id = ?
`)

var identityProviderGroupRename = RegisterStmt(`
UPDATE identity_provider_groups SET name = ? WHERE name = ?
`)

// identityProviderGroupColumns returns a string of column names to be used with a SELECT statement for the entity.
// Use this function when building statements to retrieve database entries matching the IdentityProviderGroup entity.
func identityProviderGroupColumns() string {
	return "identity_providers_groups.id, identity_providers_groups.name"
}

// getIdentityProviderGroups can be used to run handwritten sql.Stmts to return a slice of objects.
func getIdentityProviderGroups(ctx context.Context, stmt *sql.Stmt, args ...any) ([]IdentityProviderGroup, error) {
	objects := make([]IdentityProviderGroup, 0)

	dest := func(scan func(dest ...any) error) error {
		i := IdentityProviderGroup{}
		err := scan(&i.ID, &i.Name)
		if err != nil {
			return err
		}

		objects = append(objects, i)

		return nil
	}

	err := query.SelectObjects(ctx, stmt, dest, args...)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch from \"identity_providers_groups\" table: %w", err)
	}

	return objects, nil
}

// getIdentityProviderGroupsRaw can be used to run handwritten query strings to return a slice of objects.
func getIdentityProviderGroupsRaw(ctx context.Context, tx *sql.Tx, sql string, args ...any) ([]IdentityProviderGroup, error) {
	objects := make([]IdentityProviderGroup, 0)

	dest := func(scan func(dest ...any) error) error {
		i := IdentityProviderGroup{}
		err := scan(&i.ID, &i.Name)
		if err != nil {
			return err
		}

		objects = append(objects, i)

		return nil
	}

	err := query.Scan(ctx, tx, sql, dest, args...)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch from \"identity_providers_groups\" table: %w", err)
	}

	return objects, nil
}

// GetIdentityProviderGroups returns all available identity_provider_groups.
// generator: identity_provider_group GetMany
func GetIdentityProviderGroups(ctx context.Context, tx *sql.Tx, filters ...IdentityProviderGroupFilter) ([]IdentityProviderGroup, error) {
	var err error

	// Result slice.
	objects := make([]IdentityProviderGroup, 0)

	// Pick the prepared statement and arguments to use based on active criteria.
	var sqlStmt *sql.Stmt
	args := []any{}
	queryParts := [2]string{}

	if len(filters) == 0 {
		sqlStmt, err = Stmt(tx, identityProviderGroupObjects)
		if err != nil {
			return nil, fmt.Errorf("Failed to get \"identityProviderGroupObjects\" prepared statement: %w", err)
		}
	}

	for i, filter := range filters {
		if filter.Name != nil && filter.ID == nil {
			args = append(args, []any{filter.Name}...)
			if len(filters) == 1 {
				sqlStmt, err = Stmt(tx, identityProviderGroupObjectsByName)
				if err != nil {
					return nil, fmt.Errorf("Failed to get \"identityProviderGroupObjectsByName\" prepared statement: %w", err)
				}

				break
			}

			query, err := StmtString(identityProviderGroupObjectsByName)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"identityProviderGroupObjects\" prepared statement: %w", err)
			}

			parts := strings.SplitN(query, "ORDER BY", 2)
			if i == 0 {
				copy(queryParts[:], parts)
				continue
			}

			_, where, _ := strings.Cut(parts[0], "WHERE")
			queryParts[0] += "OR" + where
		} else if filter.ID != nil && filter.Name == nil {
			args = append(args, []any{filter.ID}...)
			if len(filters) == 1 {
				sqlStmt, err = Stmt(tx, identityProviderGroupObjectsByID)
				if err != nil {
					return nil, fmt.Errorf("Failed to get \"identityProviderGroupObjectsByID\" prepared statement: %w", err)
				}

				break
			}

			query, err := StmtString(identityProviderGroupObjectsByID)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"identityProviderGroupObjects\" prepared statement: %w", err)
			}

			parts := strings.SplitN(query, "ORDER BY", 2)
			if i == 0 {
				copy(queryParts[:], parts)
				continue
			}

			_, where, _ := strings.Cut(parts[0], "WHERE")
			queryParts[0] += "OR" + where
		} else if filter.ID == nil && filter.Name == nil {
			return nil, fmt.Errorf("Cannot filter on empty IdentityProviderGroupFilter")
		} else {
			return nil, fmt.Errorf("No statement exists for the given Filter")
		}
	}

	// Select.
	if sqlStmt != nil {
		objects, err = getIdentityProviderGroups(ctx, sqlStmt, args...)
	} else {
		queryStr := strings.Join(queryParts[:], "ORDER BY")
		objects, err = getIdentityProviderGroupsRaw(ctx, tx, queryStr, args...)
	}

	if err != nil {
		return nil, fmt.Errorf("Failed to fetch from \"identity_providers_groups\" table: %w", err)
	}

	return objects, nil
}

// GetIdentityProviderGroup returns the identity_provider_group with the given key.
// generator: identity_provider_group GetOne
func GetIdentityProviderGroup(ctx context.Context, tx *sql.Tx, name string) (*IdentityProviderGroup, error) {
	filter := IdentityProviderGroupFilter{}
	filter.Name = &name

	objects, err := GetIdentityProviderGroups(ctx, tx, filter)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch from \"identity_providers_groups\" table: %w", err)
	}

	switch len(objects) {
	case 0:
		return nil, api.StatusErrorf(http.StatusNotFound, "IdentityProviderGroup not found")
	case 1:
		return &objects[0], nil
	default:
		return nil, fmt.Errorf("More than one \"identity_providers_groups\" entry matches")
	}
}

// GetIdentityProviderGroupID return the ID of the identity_provider_group with the given key.
// generator: identity_provider_group ID
func GetIdentityProviderGroupID(ctx context.Context, tx *sql.Tx, name string) (int64, error) {
	stmt, err := Stmt(tx, identityProviderGroupID)
	if err != nil {
		return -1, fmt.Errorf("Failed to get \"identityProviderGroupID\" prepared statement: %w", err)
	}

	row := stmt.QueryRowContext(ctx, name)
	var id int64
	err = row.Scan(&id)
	if errors.Is(err, sql.ErrNoRows) {
		return -1, api.StatusErrorf(http.StatusNotFound, "IdentityProviderGroup not found")
	}

	if err != nil {
		return -1, fmt.Errorf("Failed to get \"identity_providers_groups\" ID: %w", err)
	}

	return id, nil
}

// IdentityProviderGroupExists checks if a identity_provider_group with the given key exists.
// generator: identity_provider_group Exists
func IdentityProviderGroupExists(ctx context.Context, tx *sql.Tx, name string) (bool, error) {
	_, err := GetIdentityProviderGroupID(ctx, tx, name)
	if err != nil {
		if api.StatusErrorCheck(err, http.StatusNotFound) {
			return false, nil
		}

		return false, err
	}

	return true, nil
}

// CreateIdentityProviderGroup adds a new identity_provider_group to the database.
// generator: identity_provider_group Create
func CreateIdentityProviderGroup(ctx context.Context, tx *sql.Tx, object IdentityProviderGroup) (int64, error) {
	// Check if a identity_provider_group with the same key exists.
	exists, err := IdentityProviderGroupExists(ctx, tx, object.Name)
	if err != nil {
		return -1, fmt.Errorf("Failed to check for duplicates: %w", err)
	}

	if exists {
		return -1, api.StatusErrorf(http.StatusConflict, "This \"identity_providers_groups\" entry already exists")
	}

	args := make([]any, 1)

	// Populate the statement arguments.
	args[0] = object.Name

	// Prepared statement to use.
	stmt, err := Stmt(tx, identityProviderGroupCreate)
	if err != nil {
		return -1, fmt.Errorf("Failed to get \"identityProviderGroupCreate\" prepared statement: %w", err)
	}

	// Execute the statement.
	result, err := stmt.Exec(args...)
	if err != nil {
		return -1, fmt.Errorf("Failed to create \"identity_providers_groups\" entry: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return -1, fmt.Errorf("Failed to fetch \"identity_providers_groups\" entry ID: %w", err)
	}

	return id, nil
}

// DeleteIdentityProviderGroup deletes the identity_provider_group matching the given key parameters.
// generator: identity_provider_group DeleteOne-by-Name
func DeleteIdentityProviderGroup(ctx context.Context, tx *sql.Tx, name string) error {
	stmt, err := Stmt(tx, identityProviderGroupDeleteByName)
	if err != nil {
		return fmt.Errorf("Failed to get \"identityProviderGroupDeleteByName\" prepared statement: %w", err)
	}

	result, err := stmt.Exec(name)
	if err != nil {
		return fmt.Errorf("Delete \"identity_providers_groups\": %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n == 0 {
		return api.StatusErrorf(http.StatusNotFound, "IdentityProviderGroup not found")
	} else if n > 1 {
		return fmt.Errorf("Query deleted %d IdentityProviderGroup rows instead of 1", n)
	}

	return nil
}

// UpdateIdentityProviderGroup updates the identity_provider_group matching the given key parameters.
// generator: identity_provider_group Update
func UpdateIdentityProviderGroup(ctx context.Context, tx *sql.Tx, name string, object IdentityProviderGroup) error {
	id, err := GetIdentityProviderGroupID(ctx, tx, name)
	if err != nil {
		return err
	}

	stmt, err := Stmt(tx, identityProviderGroupUpdate)
	if err != nil {
		return fmt.Errorf("Failed to get \"identityProviderGroupUpdate\" prepared statement: %w", err)
	}

	result, err := stmt.Exec(object.Name, id)
	if err != nil {
		return fmt.Errorf("Update \"identity_providers_groups\" entry failed: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query updated %d rows instead of 1", n)
	}

	return nil
}

// RenameIdentityProviderGroup renames the identity_provider_group matching the given key parameters.
// generator: identity_provider_group Rename
func RenameIdentityProviderGroup(ctx context.Context, tx *sql.Tx, name string, to string) error {
	stmt, err := Stmt(tx, identityProviderGroupRename)
	if err != nil {
		return fmt.Errorf("Failed to get \"identityProviderGroupRename\" prepared statement: %w", err)
	}

	result, err := stmt.Exec(to, name)
	if err != nil {
		return fmt.Errorf("Rename IdentityProviderGroup failed: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows failed: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query affected %d rows instead of 1", n)
	}

	return nil
}
