// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.30.0
// source: servers.sql

package sqlc

import (
	"context"
	"time"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5/pgtype"
)

const deleteOrphanedEntryVersions = `-- name: DeleteOrphanedEntryVersions :exec
WITH subset AS (
    SELECT v.id
      FROM entry_version v
      JOIN registry_entry e ON v.entry_id = e.id
     WHERE e.source_id = $1
       AND e.entry_type = $2
       AND v.id != ALL($3::UUID[])
)
DELETE FROM entry_version v
WHERE v.id IN (SELECT id FROM subset)
`

type DeleteOrphanedEntryVersionsParams struct {
	SourceID  uuid.UUID   `json:"source_id"`
	EntryType EntryType   `json:"entry_type"`
	KeepIds   []uuid.UUID `json:"keep_ids"`
}

func (q *Queries) DeleteOrphanedEntryVersions(ctx context.Context, arg DeleteOrphanedEntryVersionsParams) error {
	_, err := q.db.Exec(ctx, deleteOrphanedEntryVersions, arg.SourceID, arg.EntryType, arg.KeepIds)
	return err
}

const deleteServerIconsByServerId = `-- name: DeleteServerIconsByServerId :exec
DELETE FROM mcp_server_icon
WHERE server_id = $1
`

func (q *Queries) DeleteServerIconsByServerId(ctx context.Context, serverID uuid.UUID) error {
	_, err := q.db.Exec(ctx, deleteServerIconsByServerId, serverID)
	return err
}

const deleteServerPackagesByServerId = `-- name: DeleteServerPackagesByServerId :exec
DELETE FROM mcp_server_package
WHERE server_id = $1
`

func (q *Queries) DeleteServerPackagesByServerId(ctx context.Context, serverID uuid.UUID) error {
	_, err := q.db.Exec(ctx, deleteServerPackagesByServerId, serverID)
	return err
}

const deleteServerRemotesByServerId = `-- name: DeleteServerRemotesByServerId :exec
DELETE FROM mcp_server_remote
WHERE server_id = $1
`

func (q *Queries) DeleteServerRemotesByServerId(ctx context.Context, serverID uuid.UUID) error {
	_, err := q.db.Exec(ctx, deleteServerRemotesByServerId, serverID)
	return err
}

const deleteServersByRegistry = `-- name: DeleteServersByRegistry :exec
WITH registry_entries AS (
    SELECT e.id
      FROM registry_entry e
      JOIN entry_version v ON v.entry_id = e.id
      JOIN mcp_server s ON v.id = s.version_id
     WHERE e.source_id = $1
)
DELETE FROM registry_entry
 WHERE id IN (SELECT id FROM registry_entries)
`

func (q *Queries) DeleteServersByRegistry(ctx context.Context, sourceID uuid.UUID) error {
	_, err := q.db.Exec(ctx, deleteServersByRegistry, sourceID)
	return err
}

const getServerIDsByRegistryNameVersion = `-- name: GetServerIDsByRegistryNameVersion :many
SELECT s.version_id, e.name, v.version
  FROM entry_version v
  JOIN registry_entry e ON e.id = v.entry_id
  JOIN mcp_server s ON v.id = s.version_id
 WHERE e.source_id = $1
`

type GetServerIDsByRegistryNameVersionRow struct {
	VersionID uuid.UUID `json:"version_id"`
	Name      string    `json:"name"`
	Version   string    `json:"version"`
}

func (q *Queries) GetServerIDsByRegistryNameVersion(ctx context.Context, sourceID uuid.UUID) ([]GetServerIDsByRegistryNameVersionRow, error) {
	rows, err := q.db.Query(ctx, getServerIDsByRegistryNameVersion, sourceID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []GetServerIDsByRegistryNameVersionRow{}
	for rows.Next() {
		var i GetServerIDsByRegistryNameVersionRow
		if err := rows.Scan(&i.VersionID, &i.Name, &i.Version); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getServerVersion = `-- name: GetServerVersion :many
SELECT src.source_type as registry_type,
       v.id,
       e.name,
       v.version,
       (l.latest_version_id IS NOT NULL)::boolean AS is_latest,
       v.created_at,
       v.updated_at,
       v.description,
       v.title,
       s.website,
       s.upstream_meta,
       s.server_meta,
       s.repository_url,
       s.repository_id,
       s.repository_subfolder,
       s.repository_type,
       e.claims,
       rs.source_id,
       -- Sources not linked to the requested registry have no position; default to max int16
       -- so they sort after all explicitly positioned sources (lower position = higher priority).
       COALESCE(rs.position, 32767)::integer AS position
  FROM entry_version v
  JOIN registry_entry e ON e.id = v.entry_id
  JOIN registry_source rs ON rs.source_id = e.source_id
                          AND rs.registry_id = $1::uuid
  JOIN source src ON e.source_id = src.id
  JOIN mcp_server s ON s.version_id = v.id
  LEFT JOIN latest_entry_version l ON v.id = l.latest_version_id
 WHERE v.name = $2
  AND (
       v.version = $3
       OR ($3 = 'latest' AND l.latest_version_id = v.id)
   )
   AND ($4::text IS NULL OR src.name = $4::text)
   AND (
       $5::integer IS NULL
       OR (rs.position > $5::integer
           AND rs.source_id > $6::uuid
       )
   )
 ORDER BY rs.position ASC, rs.source_id ASC
 LIMIT $7::bigint
`

type GetServerVersionParams struct {
	RegistryID     uuid.UUID   `json:"registry_id"`
	Name           string      `json:"name"`
	Version        string      `json:"version"`
	SourceName     *string     `json:"source_name"`
	CursorPosition pgtype.Int4 `json:"cursor_position"`
	CursorSourceID *uuid.UUID  `json:"cursor_source_id"`
	Size           int64       `json:"size"`
}

type GetServerVersionRow struct {
	RegistryType        string     `json:"registry_type"`
	ID                  uuid.UUID  `json:"id"`
	Name                string     `json:"name"`
	Version             string     `json:"version"`
	IsLatest            bool       `json:"is_latest"`
	CreatedAt           *time.Time `json:"created_at"`
	UpdatedAt           *time.Time `json:"updated_at"`
	Description         *string    `json:"description"`
	Title               *string    `json:"title"`
	Website             *string    `json:"website"`
	UpstreamMeta        []byte     `json:"upstream_meta"`
	ServerMeta          []byte     `json:"server_meta"`
	RepositoryUrl       *string    `json:"repository_url"`
	RepositoryID        *string    `json:"repository_id"`
	RepositorySubfolder *string    `json:"repository_subfolder"`
	RepositoryType      *string    `json:"repository_type"`
	Claims              []byte     `json:"claims"`
	SourceID            uuid.UUID  `json:"source_id"`
	Position            int32      `json:"position"`
}

// Despite the name, this query returns multiple rows. The actual number of
// records is bounded by the number of sources that provide the same name and
// version, which we currently don't expect to be more than a few.
// Cursor-based pagination using (position, source_id) compound cursor.
// position is the sort key but may not be unique; source_id is the tiebreaker.
func (q *Queries) GetServerVersion(ctx context.Context, arg GetServerVersionParams) ([]GetServerVersionRow, error) {
	rows, err := q.db.Query(ctx, getServerVersion,
		arg.RegistryID,
		arg.Name,
		arg.Version,
		arg.SourceName,
		arg.CursorPosition,
		arg.CursorSourceID,
		arg.Size,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []GetServerVersionRow{}
	for rows.Next() {
		var i GetServerVersionRow
		if err := rows.Scan(
			&i.RegistryType,
			&i.ID,
			&i.Name,
			&i.Version,
			&i.IsLatest,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Description,
			&i.Title,
			&i.Website,
			&i.UpstreamMeta,
			&i.ServerMeta,
			&i.RepositoryUrl,
			&i.RepositoryID,
			&i.RepositorySubfolder,
			&i.RepositoryType,
			&i.Claims,
			&i.SourceID,
			&i.Position,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getServerVersionBySourceName = `-- name: GetServerVersionBySourceName :one
SELECT src.source_type as registry_type,
       v.id,
       e.name,
       v.version,
       (l.latest_version_id IS NOT NULL)::boolean AS is_latest,
       v.created_at,
       v.updated_at,
       v.description,
       v.title,
       s.website,
       s.upstream_meta,
       s.server_meta,
       s.repository_url,
       s.repository_id,
       s.repository_subfolder,
       s.repository_type,
       e.claims,
       0::integer AS position
  FROM mcp_server s
  JOIN entry_version v ON s.version_id = v.id
  JOIN registry_entry e ON v.entry_id = e.id
  JOIN source src ON e.source_id = src.id
  LEFT JOIN latest_entry_version l ON v.id = l.latest_version_id
 WHERE v.name = $1
   AND v.version = $2
   AND src.name = $3
`

type GetServerVersionBySourceNameParams struct {
	Name       string `json:"name"`
	Version    string `json:"version"`
	SourceName string `json:"source_name"`
}

type GetServerVersionBySourceNameRow struct {
	RegistryType        string     `json:"registry_type"`
	ID                  uuid.UUID  `json:"id"`
	Name                string     `json:"name"`
	Version             string     `json:"version"`
	IsLatest            bool       `json:"is_latest"`
	CreatedAt           *time.Time `json:"created_at"`
	UpdatedAt           *time.Time `json:"updated_at"`
	Description         *string    `json:"description"`
	Title               *string    `json:"title"`
	Website             *string    `json:"website"`
	UpstreamMeta        []byte     `json:"upstream_meta"`
	ServerMeta          []byte     `json:"server_meta"`
	RepositoryUrl       *string    `json:"repository_url"`
	RepositoryID        *string    `json:"repository_id"`
	RepositorySubfolder *string    `json:"repository_subfolder"`
	RepositoryType      *string    `json:"repository_type"`
	Claims              []byte     `json:"claims"`
	Position            int32      `json:"position"`
}

// Source-scoped variant of GetServerVersion used by the publish fetch-back path.
// source_name and version are required; registry filtering is not applied.
func (q *Queries) GetServerVersionBySourceName(ctx context.Context, arg GetServerVersionBySourceNameParams) (GetServerVersionBySourceNameRow, error) {
	row := q.db.QueryRow(ctx, getServerVersionBySourceName, arg.Name, arg.Version, arg.SourceName)
	var i GetServerVersionBySourceNameRow
	err := row.Scan(
		&i.RegistryType,
		&i.ID,
		&i.Name,
		&i.Version,
		&i.IsLatest,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Description,
		&i.Title,
		&i.Website,
		&i.UpstreamMeta,
		&i.ServerMeta,
		&i.RepositoryUrl,
		&i.RepositoryID,
		&i.RepositorySubfolder,
		&i.RepositoryType,
		&i.Claims,
		&i.Position,
	)
	return i, err
}

const insertServerIcon = `-- name: InsertServerIcon :exec
INSERT INTO mcp_server_icon (
    server_id,
    source_uri,
    mime_type,
    theme
) VALUES (
    $1,
    $2,
    $3,
    $4
)
`

type InsertServerIconParams struct {
	ServerID  uuid.UUID `json:"server_id"`
	SourceUri string    `json:"source_uri"`
	MimeType  string    `json:"mime_type"`
	Theme     IconTheme `json:"theme"`
}

func (q *Queries) InsertServerIcon(ctx context.Context, arg InsertServerIconParams) error {
	_, err := q.db.Exec(ctx, insertServerIcon,
		arg.ServerID,
		arg.SourceUri,
		arg.MimeType,
		arg.Theme,
	)
	return err
}

const insertServerPackage = `-- name: InsertServerPackage :exec
INSERT INTO mcp_server_package (
    server_id,
    registry_type,
    pkg_registry_url,
    pkg_identifier,
    pkg_version,
    runtime_hint,
    runtime_arguments,
    package_arguments,
    env_vars,
    sha256_hash,
    transport,
    transport_url,
    transport_headers
) VALUES (
    $1,
    $2,
    $3,
    $4,
    $5,
    $6,
    $7,
    $8,
    $9,
    $10,
    $11,
    $12,
    $13
)
`

type InsertServerPackageParams struct {
	ServerID         uuid.UUID `json:"server_id"`
	RegistryType     string    `json:"registry_type"`
	PkgRegistryUrl   string    `json:"pkg_registry_url"`
	PkgIdentifier    string    `json:"pkg_identifier"`
	PkgVersion       string    `json:"pkg_version"`
	RuntimeHint      *string   `json:"runtime_hint"`
	RuntimeArguments []string  `json:"runtime_arguments"`
	PackageArguments []string  `json:"package_arguments"`
	EnvVars          []byte    `json:"env_vars"`
	Sha256Hash       *string   `json:"sha256_hash"`
	Transport        string    `json:"transport"`
	TransportUrl     *string   `json:"transport_url"`
	TransportHeaders []byte    `json:"transport_headers"`
}

// TODO: this seems unused
func (q *Queries) InsertServerPackage(ctx context.Context, arg InsertServerPackageParams) error {
	_, err := q.db.Exec(ctx, insertServerPackage,
		arg.ServerID,
		arg.RegistryType,
		arg.PkgRegistryUrl,
		arg.PkgIdentifier,
		arg.PkgVersion,
		arg.RuntimeHint,
		arg.RuntimeArguments,
		arg.PackageArguments,
		arg.EnvVars,
		arg.Sha256Hash,
		arg.Transport,
		arg.TransportUrl,
		arg.TransportHeaders,
	)
	return err
}

const insertServerRemote = `-- name: InsertServerRemote :exec
INSERT INTO mcp_server_remote (
    server_id,
    transport,
    transport_url,
    transport_headers
) VALUES (
    $1,
    $2,
    $3,
    $4
)
`

type InsertServerRemoteParams struct {
	ServerID         uuid.UUID `json:"server_id"`
	Transport        string    `json:"transport"`
	TransportUrl     string    `json:"transport_url"`
	TransportHeaders []byte    `json:"transport_headers"`
}

func (q *Queries) InsertServerRemote(ctx context.Context, arg InsertServerRemoteParams) error {
	_, err := q.db.Exec(ctx, insertServerRemote,
		arg.ServerID,
		arg.Transport,
		arg.TransportUrl,
		arg.TransportHeaders,
	)
	return err
}

const insertServerVersion = `-- name: InsertServerVersion :one
INSERT INTO mcp_server (
    version_id,
    website,
    upstream_meta,
    server_meta,
    repository_url,
    repository_id,
    repository_subfolder,
    repository_type
) VALUES (
    $1,
    $2,
    $3,
    $4,
    $5,
    $6,
    $7,
    $8
)
RETURNING version_id
`

type InsertServerVersionParams struct {
	VersionID           uuid.UUID `json:"version_id"`
	Website             *string   `json:"website"`
	UpstreamMeta        []byte    `json:"upstream_meta"`
	ServerMeta          []byte    `json:"server_meta"`
	RepositoryUrl       *string   `json:"repository_url"`
	RepositoryID        *string   `json:"repository_id"`
	RepositorySubfolder *string   `json:"repository_subfolder"`
	RepositoryType      *string   `json:"repository_type"`
}

func (q *Queries) InsertServerVersion(ctx context.Context, arg InsertServerVersionParams) (uuid.UUID, error) {
	row := q.db.QueryRow(ctx, insertServerVersion,
		arg.VersionID,
		arg.Website,
		arg.UpstreamMeta,
		arg.ServerMeta,
		arg.RepositoryUrl,
		arg.RepositoryID,
		arg.RepositorySubfolder,
		arg.RepositoryType,
	)
	var version_id uuid.UUID
	err := row.Scan(&version_id)
	return version_id, err
}

const insertServerVersionForSync = `-- name: InsertServerVersionForSync :one
INSERT INTO mcp_server (
    version_id,
    website,
    upstream_meta,
    server_meta,
    repository_url,
    repository_id,
    repository_subfolder,
    repository_type
) VALUES (
    $1,
    $2,
    $3,
    $4,
    $5,
    $6,
    $7,
    $8
)
RETURNING version_id
`

type InsertServerVersionForSyncParams struct {
	VersionID           uuid.UUID `json:"version_id"`
	Website             *string   `json:"website"`
	UpstreamMeta        []byte    `json:"upstream_meta"`
	ServerMeta          []byte    `json:"server_meta"`
	RepositoryUrl       *string   `json:"repository_url"`
	RepositoryID        *string   `json:"repository_id"`
	RepositorySubfolder *string   `json:"repository_subfolder"`
	RepositoryType      *string   `json:"repository_type"`
}

func (q *Queries) InsertServerVersionForSync(ctx context.Context, arg InsertServerVersionForSyncParams) (uuid.UUID, error) {
	row := q.db.QueryRow(ctx, insertServerVersionForSync,
		arg.VersionID,
		arg.Website,
		arg.UpstreamMeta,
		arg.ServerMeta,
		arg.RepositoryUrl,
		arg.RepositoryID,
		arg.RepositorySubfolder,
		arg.RepositoryType,
	)
	var version_id uuid.UUID
	err := row.Scan(&version_id)
	return version_id, err
}

const listServerPackages = `-- name: ListServerPackages :many
SELECT p.server_id,
       p.registry_type,
       p.pkg_registry_url,
       p.pkg_identifier,
       p.pkg_version,
       p.runtime_hint,
       p.runtime_arguments,
       p.package_arguments,
       p.env_vars,
       p.sha256_hash,
       p.transport,
       p.transport_url,
       p.transport_headers
  FROM mcp_server_package p
  JOIN mcp_server s ON p.server_id = s.version_id
 WHERE s.version_id = ANY($1::UUID[])
 ORDER BY p.pkg_version DESC
`

type ListServerPackagesRow struct {
	ServerID         uuid.UUID `json:"server_id"`
	RegistryType     string    `json:"registry_type"`
	PkgRegistryUrl   string    `json:"pkg_registry_url"`
	PkgIdentifier    string    `json:"pkg_identifier"`
	PkgVersion       string    `json:"pkg_version"`
	RuntimeHint      *string   `json:"runtime_hint"`
	RuntimeArguments []string  `json:"runtime_arguments"`
	PackageArguments []string  `json:"package_arguments"`
	EnvVars          []byte    `json:"env_vars"`
	Sha256Hash       *string   `json:"sha256_hash"`
	Transport        string    `json:"transport"`
	TransportUrl     *string   `json:"transport_url"`
	TransportHeaders []byte    `json:"transport_headers"`
}

func (q *Queries) ListServerPackages(ctx context.Context, versionIds []uuid.UUID) ([]ListServerPackagesRow, error) {
	rows, err := q.db.Query(ctx, listServerPackages, versionIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListServerPackagesRow{}
	for rows.Next() {
		var i ListServerPackagesRow
		if err := rows.Scan(
			&i.ServerID,
			&i.RegistryType,
			&i.PkgRegistryUrl,
			&i.PkgIdentifier,
			&i.PkgVersion,
			&i.RuntimeHint,
			&i.RuntimeArguments,
			&i.PackageArguments,
			&i.EnvVars,
			&i.Sha256Hash,
			&i.Transport,
			&i.TransportUrl,
			&i.TransportHeaders,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listServerRemotes = `-- name: ListServerRemotes :many
SELECT r.server_id,
       r.transport,
       r.transport_url,
       r.transport_headers
  FROM mcp_server_remote r
  JOIN mcp_server s ON r.server_id = s.version_id
 WHERE s.version_id = ANY($1::UUID[])
 ORDER BY r.transport, r.transport_url
`

func (q *Queries) ListServerRemotes(ctx context.Context, versionIds []uuid.UUID) ([]McpServerRemote, error) {
	rows, err := q.db.Query(ctx, listServerRemotes, versionIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []McpServerRemote{}
	for rows.Next() {
		var i McpServerRemote
		if err := rows.Scan(
			&i.ServerID,
			&i.Transport,
			&i.TransportUrl,
			&i.TransportHeaders,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listServers = `-- name: ListServers :many
SELECT src.source_type as registry_type,
       v.id,
       e.name,
       v.version,
       (l.latest_version_id IS NOT NULL)::boolean AS is_latest,
       v.created_at,
       v.updated_at,
       v.description,
       v.title,
       s.website,
       s.upstream_meta,
       s.server_meta,
       s.repository_url,
       s.repository_id,
       s.repository_subfolder,
       s.repository_type,
       e.claims,
       -- Sources not linked to the requested registry have no position; default to max int16
       -- so they sort after all explicitly positioned sources (lower position = higher priority).
       COALESCE(rs.position, 32767)::integer AS position
  FROM mcp_server s
  JOIN entry_version v ON s.version_id = v.id
  JOIN registry_entry e ON v.entry_id = e.id
  JOIN source src ON e.source_id = src.id
  LEFT JOIN latest_entry_version l ON v.id = l.latest_version_id
  JOIN registry_source rs ON rs.source_id = e.source_id
                          AND rs.registry_id = $1::uuid
 WHERE ($2::text IS NULL OR e.name = $2::text)
   AND ($3::text IS NULL OR (
       LOWER(e.name) LIKE LOWER('%' || $3::text || '%')
       OR LOWER(v.title) LIKE LOWER('%' || $3::text || '%')
       OR LOWER(v.description) LIKE LOWER('%' || $3::text || '%')
   ))
   -- Filter by updated_since if provided
   AND ($4::timestamp with time zone IS NULL OR v.updated_at > $4::timestamp with time zone)
   -- Compound cursor comparison: (name, version) > (cursor_name, cursor_version)
   -- This ensures deterministic pagination even when timestamps are identical
   AND (
       $5::text IS NULL
       OR (v.name, v.version) > ($5::text, $6::text)
   )
   AND (
       $7::text IS NULL OR
       v.version = $7::text OR
       ($7::text = 'latest' AND l.latest_version_id = v.id)
   )
 ORDER BY v.name ASC, v.version ASC, rs.position ASC
 LIMIT $8::bigint
`

type ListServersParams struct {
	RegistryID    uuid.UUID  `json:"registry_id"`
	Name          *string    `json:"name"`
	Search        *string    `json:"search"`
	UpdatedSince  *time.Time `json:"updated_since"`
	CursorName    *string    `json:"cursor_name"`
	CursorVersion *string    `json:"cursor_version"`
	Version       *string    `json:"version"`
	Size          int64      `json:"size"`
}

type ListServersRow struct {
	RegistryType        string     `json:"registry_type"`
	ID                  uuid.UUID  `json:"id"`
	Name                string     `json:"name"`
	Version             string     `json:"version"`
	IsLatest            bool       `json:"is_latest"`
	CreatedAt           *time.Time `json:"created_at"`
	UpdatedAt           *time.Time `json:"updated_at"`
	Description         *string    `json:"description"`
	Title               *string    `json:"title"`
	Website             *string    `json:"website"`
	UpstreamMeta        []byte     `json:"upstream_meta"`
	ServerMeta          []byte     `json:"server_meta"`
	RepositoryUrl       *string    `json:"repository_url"`
	RepositoryID        *string    `json:"repository_id"`
	RepositorySubfolder *string    `json:"repository_subfolder"`
	RepositoryType      *string    `json:"repository_type"`
	Claims              []byte     `json:"claims"`
	Position            int32      `json:"position"`
}

// Cursor-based pagination using (name, version) compound cursor.
// The cursor_name and cursor_version parameters define the starting point.
// When cursor is provided, results start AFTER the specified (name, version) tuple.
// Returns position from registry_source for source priority ordering.
// When name is provided, results are filtered to versions of that specific server.
func (q *Queries) ListServers(ctx context.Context, arg ListServersParams) ([]ListServersRow, error) {
	rows, err := q.db.Query(ctx, listServers,
		arg.RegistryID,
		arg.Name,
		arg.Search,
		arg.UpdatedSince,
		arg.CursorName,
		arg.CursorVersion,
		arg.Version,
		arg.Size,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListServersRow{}
	for rows.Next() {
		var i ListServersRow
		if err := rows.Scan(
			&i.RegistryType,
			&i.ID,
			&i.Name,
			&i.Version,
			&i.IsLatest,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Description,
			&i.Title,
			&i.Website,
			&i.UpstreamMeta,
			&i.ServerMeta,
			&i.RepositoryUrl,
			&i.RepositoryID,
			&i.RepositorySubfolder,
			&i.RepositoryType,
			&i.Claims,
			&i.Position,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const upsertLatestServerVersion = `-- name: UpsertLatestServerVersion :one
INSERT INTO latest_entry_version (
    source_id,
    name,
    version,
    latest_version_id
) VALUES (
    $1,
    $2,
    $3,
    $4
) ON CONFLICT (source_id, name)
  DO UPDATE SET
    version = $3,
    latest_version_id = $4
RETURNING latest_version_id
`

type UpsertLatestServerVersionParams struct {
	SourceID  uuid.UUID `json:"source_id"`
	Name      string    `json:"name"`
	Version   string    `json:"version"`
	VersionID uuid.UUID `json:"version_id"`
}

func (q *Queries) UpsertLatestServerVersion(ctx context.Context, arg UpsertLatestServerVersionParams) (uuid.UUID, error) {
	row := q.db.QueryRow(ctx, upsertLatestServerVersion,
		arg.SourceID,
		arg.Name,
		arg.Version,
		arg.VersionID,
	)
	var latest_version_id uuid.UUID
	err := row.Scan(&latest_version_id)
	return latest_version_id, err
}

const upsertServerVersionForSync = `-- name: UpsertServerVersionForSync :one
INSERT INTO mcp_server (
    version_id,
    website,
    upstream_meta,
    server_meta,
    repository_url,
    repository_id,
    repository_subfolder,
    repository_type
) VALUES (
    $1,
    $2,
    $3,
    $4,
    $5,
    $6,
    $7,
    $8
)
ON CONFLICT (version_id)
DO UPDATE SET
    website = $2,
    upstream_meta = $3,
    server_meta = $4,
    repository_url = $5,
    repository_id = $6,
    repository_subfolder = $7,
    repository_type = $8
RETURNING version_id
`

type UpsertServerVersionForSyncParams struct {
	VersionID           uuid.UUID `json:"version_id"`
	Website             *string   `json:"website"`
	UpstreamMeta        []byte    `json:"upstream_meta"`
	ServerMeta          []byte    `json:"server_meta"`
	RepositoryUrl       *string   `json:"repository_url"`
	RepositoryID        *string   `json:"repository_id"`
	RepositorySubfolder *string   `json:"repository_subfolder"`
	RepositoryType      *string   `json:"repository_type"`
}

func (q *Queries) UpsertServerVersionForSync(ctx context.Context, arg UpsertServerVersionForSyncParams) (uuid.UUID, error) {
	row := q.db.QueryRow(ctx, upsertServerVersionForSync,
		arg.VersionID,
		arg.Website,
		arg.UpstreamMeta,
		arg.ServerMeta,
		arg.RepositoryUrl,
		arg.RepositoryID,
		arg.RepositorySubfolder,
		arg.RepositoryType,
	)
	var version_id uuid.UUID
	err := row.Scan(&version_id)
	return version_id, err
}
