//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 networkObjects = RegisterStmt(`
SELECT networks.id, projects.name AS project, networks.name, networks.description, networks.type, networks.state
  FROM networks
  JOIN projects ON networks.project_id = projects.id
  ORDER BY networks.id
`)

var networkObjectsByState = RegisterStmt(`
SELECT networks.id, projects.name AS project, networks.name, networks.description, networks.type, networks.state
  FROM networks
  JOIN projects ON networks.project_id = projects.id
  WHERE ( networks.state = ? )
  ORDER BY networks.id
`)

var networkObjectsByProjectAndState = RegisterStmt(`
SELECT networks.id, projects.name AS project, networks.name, networks.description, networks.type, networks.state
  FROM networks
  JOIN projects ON networks.project_id = projects.id
  WHERE ( project = ? AND networks.state = ? )
  ORDER BY networks.id
`)

// networkColumns 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 Network entity.
func networkColumns() string {
	return "networks.id, projects.name AS project, networks.name, networks.description, networks.type, networks.state"
}

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

	dest := func(scan func(dest ...any) error) error {
		n := Network{}
		err := scan(&n.ID, &n.Project, &n.Name, &n.Description, &n.Type, &n.State)
		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\" table: %w", err)
	}

	return objects, nil
}

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

	dest := func(scan func(dest ...any) error) error {
		n := Network{}
		err := scan(&n.ID, &n.Project, &n.Name, &n.Description, &n.Type, &n.State)
		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\" table: %w", err)
	}

	return objects, nil
}

// GetNetworks returns all available networks.
// generator: network GetMany
func GetNetworks(ctx context.Context, db dbtx, filters ...NetworkFilter) (_ []Network, _err error) {
	defer func() {
		_err = mapErr(_err, "Network")
	}()

	var err error

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

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

				break
			}

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

				break
			}

			query, err := StmtString(networkObjectsByState)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"networkObjects\" 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.Project == nil && filter.Name == nil && filter.Type == nil && filter.State == nil {
			return nil, fmt.Errorf("Cannot filter on empty NetworkFilter")
		} else {
			return nil, errors.New("No statement exists for the given Filter")
		}
	}

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

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

	return objects, nil
}
