// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.29.0
// source: lease.sql

package sqlcv1

import (
	"context"

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

const acquireOrExtendLeases = `-- name: AcquireOrExtendLeases :many
INSERT INTO "Lease" (
    "expiresAt",
    "tenantId",
    "resourceId",
    "kind"
)
SELECT
    now() + COALESCE($1::interval, '30 seconds'::interval),
    $2::uuid,
    input."resourceId",
    $3::"LeaseKind"
FROM (
    SELECT
        unnest($4::text[]) AS "resourceId"
    ) AS input
ON CONFLICT ("tenantId", "kind", "resourceId") DO UPDATE
SET
    "expiresAt" = EXCLUDED."expiresAt"
WHERE
    "Lease"."expiresAt" < now() OR
    "Lease"."id" = ANY($5::bigint[])
RETURNING id, "expiresAt", "tenantId", "resourceId", kind
`

type AcquireOrExtendLeasesParams struct {
	LeaseDuration    pgtype.Interval `json:"leaseDuration"`
	Tenantid         uuid.UUID       `json:"tenantid"`
	Kind             LeaseKind       `json:"kind"`
	Resourceids      []string        `json:"resourceids"`
	Existingleaseids []int64         `json:"existingleaseids"`
}

// Attempts to acquire leases for a set of resources, and extends the leases if we already have them.
// Returns the acquired leases.
// On conflict, acquire the lease if the existing lease has expired.
func (q *Queries) AcquireOrExtendLeases(ctx context.Context, db DBTX, arg AcquireOrExtendLeasesParams) ([]*Lease, error) {
	rows, err := db.Query(ctx, acquireOrExtendLeases,
		arg.LeaseDuration,
		arg.Tenantid,
		arg.Kind,
		arg.Resourceids,
		arg.Existingleaseids,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*Lease
	for rows.Next() {
		var i Lease
		if err := rows.Scan(
			&i.ID,
			&i.ExpiresAt,
			&i.TenantId,
			&i.ResourceId,
			&i.Kind,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getLeasesToAcquire = `-- name: GetLeasesToAcquire :exec
SELECT
    id, "expiresAt", "tenantId", "resourceId", kind
FROM
    "Lease"
WHERE
    "tenantId" = $1::uuid
    AND "kind" = $2::"LeaseKind"
    AND "expiresAt" < now()
    AND "resourceId" = ANY($3::text[])
FOR UPDATE
`

type GetLeasesToAcquireParams struct {
	Tenantid    uuid.UUID `json:"tenantid"`
	Kind        LeaseKind `json:"kind"`
	Resourceids []string  `json:"resourceids"`
}

func (q *Queries) GetLeasesToAcquire(ctx context.Context, db DBTX, arg GetLeasesToAcquireParams) error {
	_, err := db.Exec(ctx, getLeasesToAcquire, arg.Tenantid, arg.Kind, arg.Resourceids)
	return err
}

const listActiveWorkers = `-- name: ListActiveWorkers :many
SELECT
    DISTINCT w."id",
    w."name"
FROM
    "Worker" w
JOIN
    v1_worker_slot_config wsc ON w."id" = wsc."worker_id"
WHERE
    w."tenantId" = $1::uuid
    AND w."dispatcherId" IS NOT NULL
    AND w."lastHeartbeatAt" > NOW() - INTERVAL '5 seconds'
    AND w."isActive" = true
    AND w."isPaused" = false
`

type ListActiveWorkersRow struct {
	ID   uuid.UUID `json:"id"`
	Name string    `json:"name"`
}

func (q *Queries) ListActiveWorkers(ctx context.Context, db DBTX, tenantid uuid.UUID) ([]*ListActiveWorkersRow, error) {
	rows, err := db.Query(ctx, listActiveWorkers, tenantid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*ListActiveWorkersRow
	for rows.Next() {
		var i ListActiveWorkersRow
		if err := rows.Scan(&i.ID, &i.Name); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const releaseLeases = `-- name: ReleaseLeases :many
DELETE FROM "Lease" l
USING (
    SELECT
        unnest($1::bigint[]) AS "id"
    ) AS input
WHERE
    l."id" = input."id"
RETURNING l.id, l."expiresAt", l."tenantId", l."resourceId", l.kind
`

// Releases a set of leases by their IDs. Returns the released leases.
func (q *Queries) ReleaseLeases(ctx context.Context, db DBTX, leaseids []int64) ([]*Lease, error) {
	rows, err := db.Query(ctx, releaseLeases, leaseids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*Lease
	for rows.Next() {
		var i Lease
		if err := rows.Scan(
			&i.ID,
			&i.ExpiresAt,
			&i.TenantId,
			&i.ResourceId,
			&i.Kind,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}
