package database

// 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"
	"github.com/canonical/microcluster/v2/cluster"
)

var _ = api.ServerEnvironment{}

var remoteObjects = cluster.RegisterStmt(`
SELECT remote.id, remote.name, remote.local_name
  FROM remote
  ORDER BY remote.name
`)

var remoteObjectsByName = cluster.RegisterStmt(`
SELECT remote.id, remote.name, remote.local_name
  FROM remote
  WHERE ( remote.name = ? )
  ORDER BY remote.name
`)

var remoteID = cluster.RegisterStmt(`
SELECT remote.id FROM remote
  WHERE remote.name = ?
`)

var remoteCreate = cluster.RegisterStmt(`
INSERT INTO remote (name, local_name)
  VALUES (?, ?)
`)

var remoteDeleteByName = cluster.RegisterStmt(`
DELETE FROM remote WHERE name = ?
`)

var remoteUpdate = cluster.RegisterStmt(`
UPDATE remote
  SET name = ?, local_name = ?
 WHERE id = ?
`)

// remoteColumns 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 Remote entity.
func remoteColumns() string {
	return "remote.id, remote.name, remote.local_name"
}

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

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

		objects = append(objects, r)

		return nil
	}

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

	return objects, nil
}

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

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

		objects = append(objects, r)

		return nil
	}

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

	return objects, nil
}

// GetRemotes returns all available Remotes.
// generator: Remote GetMany
func GetRemotes(ctx context.Context, tx *sql.Tx, filters ...RemoteFilter) ([]Remote, error) {
	var err error

	// Result slice.
	objects := make([]Remote, 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 = cluster.Stmt(tx, remoteObjects)
		if err != nil {
			return nil, fmt.Errorf("Failed to get \"remoteObjects\" prepared statement: %w", err)
		}
	}

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

				break
			}

			query, err := cluster.StmtString(remoteObjectsByName)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"remoteObjects\" 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.Name == nil {
			return nil, fmt.Errorf("Cannot filter on empty RemoteFilter")
		} else {
			return nil, fmt.Errorf("No statement exists for the given Filter")
		}
	}

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

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

	return objects, nil
}

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

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

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

// GetRemoteID return the ID of the Remote with the given key.
// generator: Remote ID
func GetRemoteID(ctx context.Context, tx *sql.Tx, name string) (int64, error) {
	stmt, err := cluster.Stmt(tx, remoteID)
	if err != nil {
		return -1, fmt.Errorf("Failed to get \"remoteID\" 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, "Remote not found")
	}

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

	return id, nil
}

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

		return false, err
	}

	return true, nil
}

// CreateRemote adds a new Remote to the database.
// generator: Remote Create
func CreateRemote(ctx context.Context, tx *sql.Tx, object Remote) (int64, error) {
	// Check if a Remote with the same key exists.
	exists, err := RemoteExists(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 \"remote\" entry already exists")
	}

	args := make([]any, 2)

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

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

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

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

	return id, nil
}

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

	result, err := stmt.Exec(name)
	if err != nil {
		return fmt.Errorf("Delete \"remote\": %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, "Remote not found")
	} else if n > 1 {
		return fmt.Errorf("Query deleted %d Remote rows instead of 1", n)
	}

	return nil
}

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

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

	result, err := stmt.Exec(object.Name, object.LocalName, id)
	if err != nil {
		return fmt.Errorf("Update \"remote\" 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
}
