//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 networkZoneRecordObjects = RegisterStmt(`
SELECT networks_zones_records.id, networks_zones_records.network_zone_id, networks_zones_records.name, networks_zones_records.description, networks_zones_records.entries
  FROM networks_zones_records
  ORDER BY networks_zones_records.id
`)

var networkZoneRecordObjectsByID = RegisterStmt(`
SELECT networks_zones_records.id, networks_zones_records.network_zone_id, networks_zones_records.name, networks_zones_records.description, networks_zones_records.entries
  FROM networks_zones_records
  WHERE ( networks_zones_records.id = ? )
  ORDER BY networks_zones_records.id
`)

var networkZoneRecordObjectsByName = RegisterStmt(`
SELECT networks_zones_records.id, networks_zones_records.network_zone_id, networks_zones_records.name, networks_zones_records.description, networks_zones_records.entries
  FROM networks_zones_records
  WHERE ( networks_zones_records.name = ? )
  ORDER BY networks_zones_records.id
`)

var networkZoneRecordObjectsByNetworkZoneID = RegisterStmt(`
SELECT networks_zones_records.id, networks_zones_records.network_zone_id, networks_zones_records.name, networks_zones_records.description, networks_zones_records.entries
  FROM networks_zones_records
  WHERE ( networks_zones_records.network_zone_id = ? )
  ORDER BY networks_zones_records.id
`)

var networkZoneRecordObjectsByNetworkZoneIDAndName = RegisterStmt(`
SELECT networks_zones_records.id, networks_zones_records.network_zone_id, networks_zones_records.name, networks_zones_records.description, networks_zones_records.entries
  FROM networks_zones_records
  WHERE ( networks_zones_records.network_zone_id = ? AND networks_zones_records.name = ? )
  ORDER BY networks_zones_records.id
`)

var networkZoneRecordObjectsByNetworkZoneIDAndID = RegisterStmt(`
SELECT networks_zones_records.id, networks_zones_records.network_zone_id, networks_zones_records.name, networks_zones_records.description, networks_zones_records.entries
  FROM networks_zones_records
  WHERE ( networks_zones_records.network_zone_id = ? AND networks_zones_records.id = ? )
  ORDER BY networks_zones_records.id
`)

var networkZoneRecordID = RegisterStmt(`
SELECT networks_zones_records.id FROM networks_zones_records
  WHERE networks_zones_records.network_zone_id = ? AND networks_zones_records.name = ?
`)

var networkZoneRecordCreate = RegisterStmt(`
INSERT INTO networks_zones_records (network_zone_id, name, description, entries)
  VALUES (?, ?, ?, ?)
`)

var networkZoneRecordRename = RegisterStmt(`
UPDATE networks_zones_records SET name = ? WHERE network_zone_id = ? AND name = ?
`)

var networkZoneRecordUpdate = RegisterStmt(`
UPDATE networks_zones_records
  SET network_zone_id = ?, name = ?, description = ?, entries = ?
 WHERE id = ?
`)

var networkZoneRecordDeleteByNetworkZoneIDAndID = RegisterStmt(`
DELETE FROM networks_zones_records WHERE network_zone_id = ? AND id = ?
`)

// networkZoneRecordColumns 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 NetworkZoneRecord entity.
func networkZoneRecordColumns() string {
	return "networks_zones_records.id, networks_zones_records.network_zone_id, networks_zones_records.name, networks_zones_records.description, networks_zones_records.entries"
}

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

	dest := func(scan func(dest ...any) error) error {
		n := NetworkZoneRecord{}
		var entriesStr string
		err := scan(&n.ID, &n.NetworkZoneID, &n.Name, &n.Description, &entriesStr)
		if err != nil {
			return err
		}

		err = unmarshalJSON(entriesStr, &n.Entries)
		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_records\" table: %w", err)
	}

	return objects, nil
}

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

	dest := func(scan func(dest ...any) error) error {
		n := NetworkZoneRecord{}
		var entriesStr string
		err := scan(&n.ID, &n.NetworkZoneID, &n.Name, &n.Description, &entriesStr)
		if err != nil {
			return err
		}

		err = unmarshalJSON(entriesStr, &n.Entries)
		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_records\" table: %w", err)
	}

	return objects, nil
}

// GetNetworkZoneRecords returns all available NetworkZoneRecords.
// generator: NetworkZoneRecord GetMany
func GetNetworkZoneRecords(ctx context.Context, db dbtx, filters ...NetworkZoneRecordFilter) (_ []NetworkZoneRecord, _err error) {
	defer func() {
		_err = mapErr(_err, "NetworkZoneRecord")
	}()

	var err error

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

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

				break
			}

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

				break
			}

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

				break
			}

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

				break
			}

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

				break
			}

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

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

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

	return objects, nil
}

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

	networkZoneRecordConfig, err := GetConfig(ctx, db, "networks_zones_records", "network_zone_record", filters...)
	if err != nil {
		return nil, err
	}

	config, ok := networkZoneRecordConfig[networkZoneRecordID]
	if !ok {
		config = map[string]string{}
	}

	return config, nil
}

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

	filter := NetworkZoneRecordFilter{}
	filter.NetworkZoneID = &networkZoneID
	filter.Name = &name

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

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

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

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

	return true, nil
}

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

	args := make([]any, 4)

	// Populate the statement arguments.
	args[0] = object.NetworkZoneID
	args[1] = object.Name
	args[2] = object.Description
	marshaledEntries, err := marshalJSON(object.Entries)
	if err != nil {
		return -1, err
	}

	args[3] = marshaledEntries

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

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

	return id, nil
}

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

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

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

	}

	return nil
}

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

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

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

	return id, nil
}

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

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

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

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

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

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

	marshaledEntries, err := marshalJSON(object.Entries)
	if err != nil {
		return err
	}

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

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

	err := UpdateConfig(ctx, db, "networks_zones_records", "network_zone_record", int(networkZoneRecordID), config)
	if err != nil {
		return fmt.Errorf("Replace Config for NetworkZoneRecord failed: %w", err)
	}

	return nil
}

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

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

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

	return nil
}
