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

var networkZoneObjectsByID = RegisterStmt(`
SELECT networks_zones.id, networks_zones.project_id, projects.name AS project, networks_zones.name, networks_zones.description
  FROM networks_zones
  JOIN projects ON networks_zones.project_id = projects.id
  WHERE ( networks_zones.id = ? )
  ORDER BY networks_zones.id
`)

var networkZoneObjectsByName = RegisterStmt(`
SELECT networks_zones.id, networks_zones.project_id, projects.name AS project, networks_zones.name, networks_zones.description
  FROM networks_zones
  JOIN projects ON networks_zones.project_id = projects.id
  WHERE ( networks_zones.name = ? )
  ORDER BY networks_zones.id
`)

var networkZoneObjectsByProject = RegisterStmt(`
SELECT networks_zones.id, networks_zones.project_id, projects.name AS project, networks_zones.name, networks_zones.description
  FROM networks_zones
  JOIN projects ON networks_zones.project_id = projects.id
  WHERE ( project = ? )
  ORDER BY networks_zones.id
`)

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

var networkZoneID = RegisterStmt(`
SELECT networks_zones.id FROM networks_zones
  JOIN projects ON networks_zones.project_id = projects.id
  WHERE projects.name = ? AND networks_zones.name = ?
`)

var networkZoneCreate = RegisterStmt(`
INSERT INTO networks_zones (project_id, name, description)
  VALUES ((SELECT projects.id FROM projects WHERE projects.name = ?), ?, ?)
`)

var networkZoneRename = RegisterStmt(`
UPDATE networks_zones SET name = ? WHERE project_id = (SELECT projects.id FROM projects WHERE projects.name = ?) AND name = ?
`)

var networkZoneUpdate = RegisterStmt(`
UPDATE networks_zones
  SET project_id = (SELECT projects.id FROM projects WHERE projects.name = ?), name = ?, description = ?
 WHERE id = ?
`)

var networkZoneDeleteByID = RegisterStmt(`
DELETE FROM networks_zones WHERE id = ?
`)

// networkZoneColumns 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 NetworkZone entity.
func networkZoneColumns() string {
	return "networks_zones.id, networks_zones.project_id, projects.name AS project, networks_zones.name, networks_zones.description"
}

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

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

	return objects, nil
}

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

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

	return objects, nil
}

// GetNetworkZones returns all available NetworkZones.
// generator: NetworkZone GetMany
func GetNetworkZones(ctx context.Context, db dbtx, filters ...NetworkZoneFilter) (_ []NetworkZone, _err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZone")
	}()

	var err error

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

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

				break
			}

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

				break
			}

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

				break
			}

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

				break
			}

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

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

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

	return objects, nil
}

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

	networkZoneConfig, err := GetConfig(ctx, db, "networks_zones", "network_zone", filters...)
	if err != nil {
		return nil, err
	}

	config, ok := networkZoneConfig[networkZoneID]
	if !ok {
		config = map[string]string{}
	}

	return config, nil
}

// GetNetworkZone returns the NetworkZone with the given key.
// generator: NetworkZone GetOne
func GetNetworkZone(ctx context.Context, db dbtx, project string, name string) (_ *NetworkZone, _err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZone")
	}()

	filter := NetworkZoneFilter{}
	filter.Project = &project
	filter.Name = &name

	objects, err := GetNetworkZones(ctx, db, filter)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch from \"networks_zones\" 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_zones\" entry matches")
	}
}

// NetworkZoneExists checks if a NetworkZone with the given key exists.
// generator: NetworkZone Exists
func NetworkZoneExists(ctx context.Context, db dbtx, project string, name string) (_ bool, _err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZone")
	}()

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

	row := stmt.QueryRowContext(ctx, project, name)
	var id int64
	err = row.Scan(&id)
	if errors.Is(err, sql.ErrNoRows) {
		return false, nil
	}

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

	return true, nil
}

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

	args := make([]any, 3)

	// Populate the statement arguments.
	args[0] = object.Project
	args[1] = object.Name
	args[2] = object.Description

	// Prepared statement to use.
	stmt, err := Stmt(db, networkZoneCreate)
	if err != nil {
		return -1, fmt.Errorf("Failed to get \"networkZoneCreate\" 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_zones\" entry: %w", err)
	}

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

	return id, nil
}

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

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

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

	}

	return nil
}

// GetNetworkZoneID return the ID of the NetworkZone with the given key.
// generator: NetworkZone ID
func GetNetworkZoneID(ctx context.Context, db tx, project string, name string) (_ int64, _err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZone")
	}()

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

	row := stmt.QueryRowContext(ctx, project, name)
	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_zones\" ID: %w", err)
	}

	return id, nil
}

// RenameNetworkZone renames the NetworkZone matching the given key parameters.
// generator: NetworkZone Rename
func RenameNetworkZone(ctx context.Context, db dbtx, project string, name string, to string) (_err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZone")
	}()

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

	result, err := stmt.Exec(to, project, name)
	if err != nil {
		return fmt.Errorf("Rename NetworkZone 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
}

// UpdateNetworkZone updates the NetworkZone matching the given key parameters.
// generator: NetworkZone Update
func UpdateNetworkZone(ctx context.Context, db tx, project string, name string, object NetworkZone) (_err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZone")
	}()

	id, err := GetNetworkZoneID(ctx, db, project, name)
	if err != nil {
		return err
	}

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

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

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

	err := UpdateConfig(ctx, db, "networks_zones", "network_zone", int(networkZoneID), config)
	if err != nil {
		return fmt.Errorf("Replace Config for NetworkZone failed: %w", err)
	}

	return nil
}

// DeleteNetworkZone deletes the NetworkZone matching the given key parameters.
// generator: NetworkZone DeleteOne-by-ID
func DeleteNetworkZone(ctx context.Context, db dbtx, id int) (_err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZone")
	}()

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

	result, err := stmt.Exec(id)
	if err != nil {
		return fmt.Errorf("Delete \"networks_zones\": %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 NetworkZone rows instead of 1", n)
	}

	return nil
}
