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 serviceGroupObjects = cluster.RegisterStmt(`
SELECT service_groups.service, service_groups.group_id, service_groups.config
  FROM service_groups
  ORDER BY service_groups.service, service_groups.group_id
`)

var serviceGroupObjectsByService = cluster.RegisterStmt(`
SELECT service_groups.service, service_groups.group_id, service_groups.config
  FROM service_groups
  WHERE ( service_groups.service = ? )
  ORDER BY service_groups.service, service_groups.group_id
`)

var serviceGroupObjectsByGroupID = cluster.RegisterStmt(`
SELECT service_groups.service, service_groups.group_id, service_groups.config
  FROM service_groups
  WHERE ( service_groups.group_id = ? )
  ORDER BY service_groups.service, service_groups.group_id
`)

var serviceGroupObjectsByServiceAndGroupID = cluster.RegisterStmt(`
SELECT service_groups.service, service_groups.group_id, service_groups.config
  FROM service_groups
  WHERE ( service_groups.service = ? AND service_groups.group_id = ? )
  ORDER BY service_groups.service, service_groups.group_id
`)

var serviceGroupID = cluster.RegisterStmt(`
SELECT service_groups.id FROM service_groups
  WHERE service_groups.service = ? AND service_groups.group_id = ?
`)

var serviceGroupCreate = cluster.RegisterStmt(`
INSERT INTO service_groups (service, group_id, config)
  VALUES (?, ?, ?)
`)

var serviceGroupDeleteByServiceAndGroupID = cluster.RegisterStmt(`
DELETE FROM service_groups WHERE service = ? AND group_id = ?
`)

var serviceGroupUpdate = cluster.RegisterStmt(`
UPDATE service_groups
  SET service = ?, group_id = ?, config = ?
 WHERE id = ?
`)

// serviceGroupColumns 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 ServiceGroup entity.
func serviceGroupColumns() string {
	return "service_groups.service, service_groups.group_id, service_groups.config"
}

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

	dest := func(scan func(dest ...any) error) error {
		s := ServiceGroup{}
		err := scan(&s.Service, &s.GroupID, &s.Config)
		if err != nil {
			return err
		}

		objects = append(objects, s)

		return nil
	}

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

	return objects, nil
}

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

	dest := func(scan func(dest ...any) error) error {
		s := ServiceGroup{}
		err := scan(&s.Service, &s.GroupID, &s.Config)
		if err != nil {
			return err
		}

		objects = append(objects, s)

		return nil
	}

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

	return objects, nil
}

// GetServiceGroups returns all available ServiceGroups.
// generator: ServiceGroup GetMany
func GetServiceGroups(ctx context.Context, tx *sql.Tx, filters ...ServiceGroupFilter) ([]ServiceGroup, error) {
	var err error

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

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

				break
			}

			query, err := cluster.StmtString(serviceGroupObjectsByServiceAndGroupID)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"serviceGroupObjects\" 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.Service != nil && filter.GroupID == nil {
			args = append(args, []any{filter.Service}...)
			if len(filters) == 1 {
				sqlStmt, err = cluster.Stmt(tx, serviceGroupObjectsByService)
				if err != nil {
					return nil, fmt.Errorf("Failed to get \"serviceGroupObjectsByService\" prepared statement: %w", err)
				}

				break
			}

			query, err := cluster.StmtString(serviceGroupObjectsByService)
			if err != nil {
				return nil, fmt.Errorf("Failed to get \"serviceGroupObjects\" 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.GroupID != nil && filter.Service == nil {
			args = append(args, []any{filter.GroupID}...)
			if len(filters) == 1 {
				sqlStmt, err = cluster.Stmt(tx, serviceGroupObjectsByGroupID)
				if err != nil {
					return nil, fmt.Errorf("Failed to get \"serviceGroupObjectsByGroupID\" prepared statement: %w", err)
				}

				break
			}

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

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

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

	return objects, nil
}

// GetServiceGroup returns the ServiceGroup with the given key.
// generator: ServiceGroup GetOne
func GetServiceGroup(ctx context.Context, tx *sql.Tx, service string, groupID string) (*ServiceGroup, error) {
	filter := ServiceGroupFilter{}
	filter.Service = &service
	filter.GroupID = &groupID

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

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

// GetServiceGroupID return the ID of the ServiceGroup with the given key.
// generator: ServiceGroup ID
func GetServiceGroupID(ctx context.Context, tx *sql.Tx, service string, groupID string) (int64, error) {
	stmt, err := cluster.Stmt(tx, serviceGroupID)
	if err != nil {
		return -1, fmt.Errorf("Failed to get \"serviceGroupID\" prepared statement: %w", err)
	}

	row := stmt.QueryRowContext(ctx, service, groupID)
	var id int64
	err = row.Scan(&id)
	if errors.Is(err, sql.ErrNoRows) {
		return -1, api.StatusErrorf(http.StatusNotFound, "ServiceGroup not found")
	}

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

	return id, nil
}

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

		return false, err
	}

	return true, nil
}

// CreateServiceGroup adds a new ServiceGroup to the database.
// generator: ServiceGroup Create
func CreateServiceGroup(ctx context.Context, tx *sql.Tx, object ServiceGroup) (int64, error) {
	// Check if a ServiceGroup with the same key exists.
	exists, err := ServiceGroupExists(ctx, tx, object.Service, object.GroupID)
	if err != nil {
		return -1, fmt.Errorf("Failed to check for duplicates: %w", err)
	}

	if exists {
		return -1, api.StatusErrorf(http.StatusConflict, "This \"service_groups\" entry already exists")
	}

	args := make([]any, 3)

	// Populate the statement arguments.
	args[0] = object.Service
	args[1] = object.GroupID
	args[2] = object.Config

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

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

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

	return id, nil
}

// DeleteServiceGroup deletes the ServiceGroup matching the given key parameters.
// generator: ServiceGroup DeleteOne-by-Service-and-GroupID
func DeleteServiceGroup(ctx context.Context, tx *sql.Tx, service string, groupID string) error {
	stmt, err := cluster.Stmt(tx, serviceGroupDeleteByServiceAndGroupID)
	if err != nil {
		return fmt.Errorf("Failed to get \"serviceGroupDeleteByServiceAndGroupID\" prepared statement: %w", err)
	}

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

	return nil
}

// UpdateServiceGroup updates the ServiceGroup matching the given key parameters.
// generator: ServiceGroup Update
func UpdateServiceGroup(ctx context.Context, tx *sql.Tx, service string, groupID string, object ServiceGroup) error {
	id, err := GetServiceGroupID(ctx, tx, service, groupID)
	if err != nil {
		return err
	}

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

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