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

// Code generated by generate-database from the incus project - DO NOT EDIT.

package cluster

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"strings"
)

var networkLoadBalancerObjects = RegisterStmt(`
SELECT networks_load_balancers.id, networks_load_balancers.network_id, networks_load_balancers.listen_address, networks_load_balancers.description, networks_load_balancers.backends, networks_load_balancers.ports
  FROM networks_load_balancers
  ORDER BY networks_load_balancers.network_id, networks_load_balancers.listen_address
`)

var networkLoadBalancerObjectsByNetworkID = RegisterStmt(`
SELECT networks_load_balancers.id, networks_load_balancers.network_id, networks_load_balancers.listen_address, networks_load_balancers.description, networks_load_balancers.backends, networks_load_balancers.ports
  FROM networks_load_balancers
  WHERE ( networks_load_balancers.network_id = ? )
  ORDER BY networks_load_balancers.network_id, networks_load_balancers.listen_address
`)

var networkLoadBalancerObjectsByNetworkIDAndListenAddress = RegisterStmt(`
SELECT networks_load_balancers.id, networks_load_balancers.network_id, networks_load_balancers.listen_address, networks_load_balancers.description, networks_load_balancers.backends, networks_load_balancers.ports
  FROM networks_load_balancers
  WHERE ( networks_load_balancers.network_id = ? AND networks_load_balancers.listen_address = ? )
  ORDER BY networks_load_balancers.network_id, networks_load_balancers.listen_address
`)

var networkLoadBalancerID = RegisterStmt(`
SELECT networks_load_balancers.id FROM networks_load_balancers
  WHERE networks_load_balancers.network_id = ? AND networks_load_balancers.listen_address = ?
`)

var networkLoadBalancerCreate = RegisterStmt(`
INSERT INTO networks_load_balancers (network_id, listen_address, description, backends, ports)
  VALUES (?, ?, ?, ?, ?)
`)

var networkLoadBalancerUpdate = RegisterStmt(`
UPDATE networks_load_balancers
  SET network_id = ?, listen_address = ?, description = ?, backends = ?, ports = ?
 WHERE id = ?
`)

var networkLoadBalancerDeleteByNetworkIDAndID = RegisterStmt(`
DELETE FROM networks_load_balancers WHERE network_id = ? AND id = ?
`)

// networkLoadBalancerColumns 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 NetworkLoadBalancer entity.
func networkLoadBalancerColumns() string {
	return "networks_load_balancers.id, networks_load_balancers.network_id, networks_load_balancers.listen_address, networks_load_balancers.description, networks_load_balancers.backends, networks_load_balancers.ports"
}

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

	dest := func(scan func(dest ...any) error) error {
		n := NetworkLoadBalancer{}
		var backendsStr string
		var portsStr string
		err := scan(&n.ID, &n.NetworkID, &n.ListenAddress, &n.Description, &backendsStr, &portsStr)
		if err != nil {
			return err
		}

		err = unmarshalJSON(backendsStr, &n.Backends)
		if err != nil {
			return err
		}

		err = unmarshalJSON(portsStr, &n.Ports)
		if err != nil {
			return err
		}

		objects = append(objects, n)

		return nil
	}

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

	return objects, nil
}

// getNetworkLoadBalancersRaw can be used to run handwritten query strings to return a slice of objects.
func getNetworkLoadBalancersRaw(ctx context.Context, db dbtx, sql string, args ...any) ([]NetworkLoadBalancer, error) {
	objects := make([]NetworkLoadBalancer, 0)

	dest := func(scan func(dest ...any) error) error {
		n := NetworkLoadBalancer{}
		var backendsStr string
		var portsStr string
		err := scan(&n.ID, &n.NetworkID, &n.ListenAddress, &n.Description, &backendsStr, &portsStr)
		if err != nil {
			return err
		}

		err = unmarshalJSON(backendsStr, &n.Backends)
		if err != nil {
			return err
		}

		err = unmarshalJSON(portsStr, &n.Ports)
		if err != nil {
			return err
		}

		objects = append(objects, n)

		return nil
	}

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

	return objects, nil
}

// GetNetworkLoadBalancers returns all available network_load_balancers.
// generator: network_load_balancer GetMany
func GetNetworkLoadBalancers(ctx context.Context, db dbtx, filters ...NetworkLoadBalancerFilter) (_ []NetworkLoadBalancer, _err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

	var err error

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

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

				break
			}

			query, err := StmtString(networkLoadBalancerObjectsByNetworkIDAndListenAddress)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"networkLoadBalancerObjects\" 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.NetworkID != nil && filter.ID == nil && filter.ListenAddress == nil {
			args = append(args, []any{filter.NetworkID}...)
			if len(filters) == 1 {
				sqlStmt, err = Stmt(db, networkLoadBalancerObjectsByNetworkID)
				if err != nil {
					return nil, fmt.Errorf("Failed to get \"networkLoadBalancerObjectsByNetworkID\" prepared statement: %w", err)
				}

				break
			}

			query, err := StmtString(networkLoadBalancerObjectsByNetworkID)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"networkLoadBalancerObjects\" 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.NetworkID == nil && filter.ListenAddress == nil {
			return nil, fmt.Errorf("Cannot filter on empty NetworkLoadBalancerFilter")
		} else {
			return nil, errors.New("No statement exists for the given Filter")
		}
	}

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

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

	return objects, nil
}

// GetNetworkLoadBalancerConfig returns all available NetworkLoadBalancer Config
// generator: network_load_balancer GetMany
func GetNetworkLoadBalancerConfig(ctx context.Context, db tx, networkLoadBalancerID int, filters ...ConfigFilter) (_ map[string]string, _err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

	networkLoadBalancerConfig, err := GetConfig(ctx, db, "networks_load_balancers", "network_load_balancer", filters...)
	if err != nil {
		return nil, err
	}

	config, ok := networkLoadBalancerConfig[networkLoadBalancerID]
	if !ok {
		config = map[string]string{}
	}

	return config, nil
}

// GetNetworkLoadBalancer returns the network_load_balancer with the given key.
// generator: network_load_balancer GetOne
func GetNetworkLoadBalancer(ctx context.Context, db dbtx, networkID int64, listenAddress string) (_ *NetworkLoadBalancer, _err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

	filter := NetworkLoadBalancerFilter{}
	filter.NetworkID = &networkID
	filter.ListenAddress = &listenAddress

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

	switch len(objects) {
	case 0:
		return nil, ErrNotFound
	case 1:
		return &objects[0], nil
	default:
		return nil, fmt.Errorf("More than one \"networks_load_balancers\" entry matches")
	}
}

// GetNetworkLoadBalancerID return the ID of the network_load_balancer with the given key.
// generator: network_load_balancer ID
func GetNetworkLoadBalancerID(ctx context.Context, db tx, networkID int64, listenAddress string) (_ int64, _err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

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

	row := stmt.QueryRowContext(ctx, networkID, listenAddress)
	var id int64
	err = row.Scan(&id)
	if errors.Is(err, sql.ErrNoRows) {
		return -1, ErrNotFound
	}

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

	return id, nil
}

// CreateNetworkLoadBalancer adds a new network_load_balancer to the database.
// generator: network_load_balancer Create
func CreateNetworkLoadBalancer(ctx context.Context, db dbtx, object NetworkLoadBalancer) (_ int64, _err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

	args := make([]any, 5)

	// Populate the statement arguments.
	args[0] = object.NetworkID
	args[1] = object.ListenAddress
	args[2] = object.Description
	marshaledBackends, err := marshalJSON(object.Backends)
	if err != nil {
		return -1, err
	}

	args[3] = marshaledBackends
	marshaledPorts, err := marshalJSON(object.Ports)
	if err != nil {
		return -1, err
	}

	args[4] = marshaledPorts

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

	// Execute the statement.
	result, err := stmt.Exec(args...)
	if err != nil && strings.HasPrefix(err.Error(), "UNIQUE constraint failed:") {
		return -1, ErrConflict
	}

	if err != nil {
		return -1, fmt.Errorf("Failed to create \"networks_load_balancers\" entry: %w", err)
	}

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

	return id, nil
}

// CreateNetworkLoadBalancerConfig adds new network_load_balancer Config to the database.
// generator: network_load_balancer Create
func CreateNetworkLoadBalancerConfig(ctx context.Context, db dbtx, networkLoadBalancerID int64, config map[string]string) (_err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

	referenceID := int(networkLoadBalancerID)
	for key, value := range config {
		insert := Config{
			ReferenceID: referenceID,
			Key:         key,
			Value:       value,
		}

		err := CreateConfig(ctx, db, "networks_load_balancers", "network_load_balancer", insert)
		if err != nil {
			return fmt.Errorf("Insert Config failed for NetworkLoadBalancer: %w", err)
		}

	}

	return nil
}

// UpdateNetworkLoadBalancer updates the network_load_balancer matching the given key parameters.
// generator: network_load_balancer Update
func UpdateNetworkLoadBalancer(ctx context.Context, db tx, networkID int64, listenAddress string, object NetworkLoadBalancer) (_err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

	id, err := GetNetworkLoadBalancerID(ctx, db, networkID, listenAddress)
	if err != nil {
		return err
	}

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

	marshaledBackends, err := marshalJSON(object.Backends)
	if err != nil {
		return err
	}

	marshaledPorts, err := marshalJSON(object.Ports)
	if err != nil {
		return err
	}

	result, err := stmt.Exec(object.NetworkID, object.ListenAddress, object.Description, marshaledBackends, marshaledPorts, id)
	if err != nil {
		return fmt.Errorf("Update \"networks_load_balancers\" 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
}

// UpdateNetworkLoadBalancerConfig updates the network_load_balancer Config matching the given key parameters.
// generator: network_load_balancer Update
func UpdateNetworkLoadBalancerConfig(ctx context.Context, db tx, networkLoadBalancerID int64, config map[string]string) (_err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

	err := UpdateConfig(ctx, db, "networks_load_balancers", "network_load_balancer", int(networkLoadBalancerID), config)
	if err != nil {
		return fmt.Errorf("Replace Config for NetworkLoadBalancer failed: %w", err)
	}

	return nil
}

// DeleteNetworkLoadBalancer deletes the network_load_balancer matching the given key parameters.
// generator: network_load_balancer DeleteOne-by-NetworkID-and-ID
func DeleteNetworkLoadBalancer(ctx context.Context, db dbtx, networkID int64, id int64) (_err error) {
	defer func() {
		_err = mapErr(_err, "Network_load_balancer")
	}()

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

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

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

	if n == 0 {
		return ErrNotFound
	} else if n > 1 {
		return fmt.Errorf("Query deleted %d NetworkLoadBalancer rows instead of 1", n)
	}

	return nil
}
