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

package keybase

import (
	"context"
	"encoding/json"
)

const archiveEnclave = `-- name: ArchiveEnclave :exec
UPDATE mpc_enclaves SET status = 'archived' WHERE id = ?
`

func (q *Queries) ArchiveEnclave(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, archiveEnclave, id)
	return err
}

const cleanExpiredDelegations = `-- name: CleanExpiredDelegations :exec
DELETE FROM ucan_delegations WHERE exp < datetime('now', '-30 days')
`

func (q *Queries) CleanExpiredDelegations(ctx context.Context) error {
	_, err := q.db.ExecContext(ctx, cleanExpiredDelegations)
	return err
}

const cleanOldInvocations = `-- name: CleanOldInvocations :exec
DELETE FROM ucan_invocations WHERE created_at < datetime('now', '-90 days')
`

func (q *Queries) CleanOldInvocations(ctx context.Context) error {
	_, err := q.db.ExecContext(ctx, cleanOldInvocations)
	return err
}

const countActiveGrants = `-- name: CountActiveGrants :one
SELECT COUNT(*) FROM grants WHERE did_id = ? AND status = 'active'
`

func (q *Queries) CountActiveGrants(ctx context.Context, didID int64) (int64, error) {
	row := q.db.QueryRowContext(ctx, countActiveGrants, didID)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const countCredentialsByDID = `-- name: CountCredentialsByDID :one
SELECT COUNT(*) FROM credentials WHERE did_id = ?
`

func (q *Queries) CountCredentialsByDID(ctx context.Context, didID int64) (int64, error) {
	row := q.db.QueryRowContext(ctx, countCredentialsByDID, didID)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const createAccount = `-- name: CreateAccount :one
INSERT INTO accounts (did_id, enclave_id, address, chain_id, coin_type, account_index, address_index, label)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
RETURNING id, did_id, enclave_id, address, chain_id, coin_type, account_index, address_index, label, is_default, created_at
`

type CreateAccountParams struct {
	DidID        int64   `json:"did_id"`
	EnclaveID    int64   `json:"enclave_id"`
	Address      string  `json:"address"`
	ChainID      string  `json:"chain_id"`
	CoinType     int64   `json:"coin_type"`
	AccountIndex int64   `json:"account_index"`
	AddressIndex int64   `json:"address_index"`
	Label        *string `json:"label"`
}

func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (Account, error) {
	row := q.db.QueryRowContext(ctx, createAccount,
		arg.DidID,
		arg.EnclaveID,
		arg.Address,
		arg.ChainID,
		arg.CoinType,
		arg.AccountIndex,
		arg.AddressIndex,
		arg.Label,
	)
	var i Account
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.EnclaveID,
		&i.Address,
		&i.ChainID,
		&i.CoinType,
		&i.AccountIndex,
		&i.AddressIndex,
		&i.Label,
		&i.IsDefault,
		&i.CreatedAt,
	)
	return i, err
}

const createCredential = `-- name: CreateCredential :one
INSERT INTO credentials (
    did_id, credential_id, public_key, public_key_alg, aaguid,
    transports, device_name, device_type, authenticator, is_discoverable, backed_up
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
RETURNING id, did_id, credential_id, public_key, public_key_alg, aaguid, sign_count, transports, device_name, device_type, authenticator, is_discoverable, backed_up, created_at, last_used
`

type CreateCredentialParams struct {
	DidID          int64           `json:"did_id"`
	CredentialID   string          `json:"credential_id"`
	PublicKey      string          `json:"public_key"`
	PublicKeyAlg   int64           `json:"public_key_alg"`
	Aaguid         *string         `json:"aaguid"`
	Transports     json.RawMessage `json:"transports"`
	DeviceName     string          `json:"device_name"`
	DeviceType     string          `json:"device_type"`
	Authenticator  *string         `json:"authenticator"`
	IsDiscoverable int64           `json:"is_discoverable"`
	BackedUp       int64           `json:"backed_up"`
}

func (q *Queries) CreateCredential(ctx context.Context, arg CreateCredentialParams) (Credential, error) {
	row := q.db.QueryRowContext(ctx, createCredential,
		arg.DidID,
		arg.CredentialID,
		arg.PublicKey,
		arg.PublicKeyAlg,
		arg.Aaguid,
		arg.Transports,
		arg.DeviceName,
		arg.DeviceType,
		arg.Authenticator,
		arg.IsDiscoverable,
		arg.BackedUp,
	)
	var i Credential
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.CredentialID,
		&i.PublicKey,
		&i.PublicKeyAlg,
		&i.Aaguid,
		&i.SignCount,
		&i.Transports,
		&i.DeviceName,
		&i.DeviceType,
		&i.Authenticator,
		&i.IsDiscoverable,
		&i.BackedUp,
		&i.CreatedAt,
		&i.LastUsed,
	)
	return i, err
}

const createDID = `-- name: CreateDID :one
INSERT INTO did_documents (did, controller, document, sequence)
VALUES (?, ?, ?, ?)
RETURNING id, did, controller, document, sequence, last_synced, created_at, updated_at
`

type CreateDIDParams struct {
	Did        string          `json:"did"`
	Controller string          `json:"controller"`
	Document   json.RawMessage `json:"document"`
	Sequence   int64           `json:"sequence"`
}

func (q *Queries) CreateDID(ctx context.Context, arg CreateDIDParams) (DidDocument, error) {
	row := q.db.QueryRowContext(ctx, createDID,
		arg.Did,
		arg.Controller,
		arg.Document,
		arg.Sequence,
	)
	var i DidDocument
	err := row.Scan(
		&i.ID,
		&i.Did,
		&i.Controller,
		&i.Document,
		&i.Sequence,
		&i.LastSynced,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const createDelegation = `-- name: CreateDelegation :one
INSERT INTO ucan_delegations (
    did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
RETURNING id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at
`

type CreateDelegationParams struct {
	DidID       int64   `json:"did_id"`
	Cid         string  `json:"cid"`
	Envelope    []byte  `json:"envelope"`
	Iss         string  `json:"iss"`
	Aud         string  `json:"aud"`
	Sub         *string `json:"sub"`
	Cmd         string  `json:"cmd"`
	Pol         *string `json:"pol"`
	Nbf         *string `json:"nbf"`
	Exp         *string `json:"exp"`
	IsRoot      int64   `json:"is_root"`
	IsPowerline int64   `json:"is_powerline"`
}

func (q *Queries) CreateDelegation(ctx context.Context, arg CreateDelegationParams) (UcanDelegation, error) {
	row := q.db.QueryRowContext(ctx, createDelegation,
		arg.DidID,
		arg.Cid,
		arg.Envelope,
		arg.Iss,
		arg.Aud,
		arg.Sub,
		arg.Cmd,
		arg.Pol,
		arg.Nbf,
		arg.Exp,
		arg.IsRoot,
		arg.IsPowerline,
	)
	var i UcanDelegation
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.Cid,
		&i.Envelope,
		&i.Iss,
		&i.Aud,
		&i.Sub,
		&i.Cmd,
		&i.Pol,
		&i.Nbf,
		&i.Exp,
		&i.IsRoot,
		&i.IsPowerline,
		&i.CreatedAt,
	)
	return i, err
}

const createEnclave = `-- name: CreateEnclave :one
INSERT INTO mpc_enclaves (
    did_id, enclave_id, public_key_hex, public_key, val_share, user_share, nonce, curve
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
RETURNING id, did_id, enclave_id, public_key_hex, public_key, val_share, user_share, nonce, curve, status, created_at, rotated_at
`

type CreateEnclaveParams struct {
	DidID        int64  `json:"did_id"`
	EnclaveID    string `json:"enclave_id"`
	PublicKeyHex string `json:"public_key_hex"`
	PublicKey    []byte `json:"public_key"`
	ValShare     []byte `json:"val_share"`
	UserShare    []byte `json:"user_share"`
	Nonce        []byte `json:"nonce"`
	Curve        string `json:"curve"`
}

func (q *Queries) CreateEnclave(ctx context.Context, arg CreateEnclaveParams) (MpcEnclafe, error) {
	row := q.db.QueryRowContext(ctx, createEnclave,
		arg.DidID,
		arg.EnclaveID,
		arg.PublicKeyHex,
		arg.PublicKey,
		arg.ValShare,
		arg.UserShare,
		arg.Nonce,
		arg.Curve,
	)
	var i MpcEnclafe
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.EnclaveID,
		&i.PublicKeyHex,
		&i.PublicKey,
		&i.ValShare,
		&i.UserShare,
		&i.Nonce,
		&i.Curve,
		&i.Status,
		&i.CreatedAt,
		&i.RotatedAt,
	)
	return i, err
}

const createGrant = `-- name: CreateGrant :one
INSERT INTO grants (did_id, service_id, delegation_cid, scopes, accounts, expires_at)
VALUES (?, ?, ?, ?, ?, ?)
RETURNING id, did_id, service_id, delegation_cid, scopes, accounts, status, granted_at, last_used, expires_at
`

type CreateGrantParams struct {
	DidID         int64           `json:"did_id"`
	ServiceID     int64           `json:"service_id"`
	DelegationCid *string         `json:"delegation_cid"`
	Scopes        json.RawMessage `json:"scopes"`
	Accounts      json.RawMessage `json:"accounts"`
	ExpiresAt     *string         `json:"expires_at"`
}

func (q *Queries) CreateGrant(ctx context.Context, arg CreateGrantParams) (Grant, error) {
	row := q.db.QueryRowContext(ctx, createGrant,
		arg.DidID,
		arg.ServiceID,
		arg.DelegationCid,
		arg.Scopes,
		arg.Accounts,
		arg.ExpiresAt,
	)
	var i Grant
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.ServiceID,
		&i.DelegationCid,
		&i.Scopes,
		&i.Accounts,
		&i.Status,
		&i.GrantedAt,
		&i.LastUsed,
		&i.ExpiresAt,
	)
	return i, err
}

const createInvocation = `-- name: CreateInvocation :one
INSERT INTO ucan_invocations (
    did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
RETURNING id, did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat, executed_at, result_cid, created_at
`

type CreateInvocationParams struct {
	DidID    int64   `json:"did_id"`
	Cid      string  `json:"cid"`
	Envelope []byte  `json:"envelope"`
	Iss      string  `json:"iss"`
	Sub      string  `json:"sub"`
	Aud      *string `json:"aud"`
	Cmd      string  `json:"cmd"`
	Prf      string  `json:"prf"`
	Exp      *string `json:"exp"`
	Iat      *string `json:"iat"`
}

func (q *Queries) CreateInvocation(ctx context.Context, arg CreateInvocationParams) (UcanInvocation, error) {
	row := q.db.QueryRowContext(ctx, createInvocation,
		arg.DidID,
		arg.Cid,
		arg.Envelope,
		arg.Iss,
		arg.Sub,
		arg.Aud,
		arg.Cmd,
		arg.Prf,
		arg.Exp,
		arg.Iat,
	)
	var i UcanInvocation
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.Cid,
		&i.Envelope,
		&i.Iss,
		&i.Sub,
		&i.Aud,
		&i.Cmd,
		&i.Prf,
		&i.Exp,
		&i.Iat,
		&i.ExecutedAt,
		&i.ResultCid,
		&i.CreatedAt,
	)
	return i, err
}

const createRevocation = `-- name: CreateRevocation :exec

INSERT INTO ucan_revocations (delegation_cid, revoked_by, invocation_cid, reason)
VALUES (?, ?, ?, ?)
`

type CreateRevocationParams struct {
	DelegationCid string  `json:"delegation_cid"`
	RevokedBy     string  `json:"revoked_by"`
	InvocationCid *string `json:"invocation_cid"`
	Reason        *string `json:"reason"`
}

// =============================================================================
// UCAN REVOCATION QUERIES
// =============================================================================
func (q *Queries) CreateRevocation(ctx context.Context, arg CreateRevocationParams) error {
	_, err := q.db.ExecContext(ctx, createRevocation,
		arg.DelegationCid,
		arg.RevokedBy,
		arg.InvocationCid,
		arg.Reason,
	)
	return err
}

const createService = `-- name: CreateService :one
INSERT INTO services (origin, name, description, logo_url, did, is_verified, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?)
RETURNING id, origin, name, description, logo_url, did, is_verified, metadata, created_at
`

type CreateServiceParams struct {
	Origin      string          `json:"origin"`
	Name        string          `json:"name"`
	Description *string         `json:"description"`
	LogoUrl     *string         `json:"logo_url"`
	Did         *string         `json:"did"`
	IsVerified  int64           `json:"is_verified"`
	Metadata    json.RawMessage `json:"metadata"`
}

func (q *Queries) CreateService(ctx context.Context, arg CreateServiceParams) (Service, error) {
	row := q.db.QueryRowContext(ctx, createService,
		arg.Origin,
		arg.Name,
		arg.Description,
		arg.LogoUrl,
		arg.Did,
		arg.IsVerified,
		arg.Metadata,
	)
	var i Service
	err := row.Scan(
		&i.ID,
		&i.Origin,
		&i.Name,
		&i.Description,
		&i.LogoUrl,
		&i.Did,
		&i.IsVerified,
		&i.Metadata,
		&i.CreatedAt,
	)
	return i, err
}

const createSession = `-- name: CreateSession :one
INSERT INTO sessions (did_id, credential_id, session_id, device_info, is_current, expires_at)
VALUES (?, ?, ?, ?, ?, ?)
RETURNING id, did_id, credential_id, session_id, device_info, is_current, last_activity, expires_at, created_at
`

type CreateSessionParams struct {
	DidID        int64           `json:"did_id"`
	CredentialID int64           `json:"credential_id"`
	SessionID    string          `json:"session_id"`
	DeviceInfo   json.RawMessage `json:"device_info"`
	IsCurrent    int64           `json:"is_current"`
	ExpiresAt    string          `json:"expires_at"`
}

func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {
	row := q.db.QueryRowContext(ctx, createSession,
		arg.DidID,
		arg.CredentialID,
		arg.SessionID,
		arg.DeviceInfo,
		arg.IsCurrent,
		arg.ExpiresAt,
	)
	var i Session
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.CredentialID,
		&i.SessionID,
		&i.DeviceInfo,
		&i.IsCurrent,
		&i.LastActivity,
		&i.ExpiresAt,
		&i.CreatedAt,
	)
	return i, err
}

const createVerificationMethod = `-- name: CreateVerificationMethod :one
INSERT INTO verification_methods (did_id, method_id, method_type, controller, public_key, purpose)
VALUES (?, ?, ?, ?, ?, ?)
RETURNING id, did_id, method_id, method_type, controller, public_key, purpose, created_at
`

type CreateVerificationMethodParams struct {
	DidID      int64  `json:"did_id"`
	MethodID   string `json:"method_id"`
	MethodType string `json:"method_type"`
	Controller string `json:"controller"`
	PublicKey  string `json:"public_key"`
	Purpose    string `json:"purpose"`
}

func (q *Queries) CreateVerificationMethod(ctx context.Context, arg CreateVerificationMethodParams) (VerificationMethod, error) {
	row := q.db.QueryRowContext(ctx, createVerificationMethod,
		arg.DidID,
		arg.MethodID,
		arg.MethodType,
		arg.Controller,
		arg.PublicKey,
		arg.Purpose,
	)
	var i VerificationMethod
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.MethodID,
		&i.MethodType,
		&i.Controller,
		&i.PublicKey,
		&i.Purpose,
		&i.CreatedAt,
	)
	return i, err
}

const deleteAccount = `-- name: DeleteAccount :exec
DELETE FROM accounts WHERE id = ? AND did_id = ?
`

type DeleteAccountParams struct {
	ID    int64 `json:"id"`
	DidID int64 `json:"did_id"`
}

func (q *Queries) DeleteAccount(ctx context.Context, arg DeleteAccountParams) error {
	_, err := q.db.ExecContext(ctx, deleteAccount, arg.ID, arg.DidID)
	return err
}

const deleteCredential = `-- name: DeleteCredential :exec
DELETE FROM credentials WHERE id = ? AND did_id = ?
`

type DeleteCredentialParams struct {
	ID    int64 `json:"id"`
	DidID int64 `json:"did_id"`
}

func (q *Queries) DeleteCredential(ctx context.Context, arg DeleteCredentialParams) error {
	_, err := q.db.ExecContext(ctx, deleteCredential, arg.ID, arg.DidID)
	return err
}

const deleteDelegation = `-- name: DeleteDelegation :exec
DELETE FROM ucan_delegations WHERE cid = ? AND did_id = ?
`

type DeleteDelegationParams struct {
	Cid   string `json:"cid"`
	DidID int64  `json:"did_id"`
}

func (q *Queries) DeleteDelegation(ctx context.Context, arg DeleteDelegationParams) error {
	_, err := q.db.ExecContext(ctx, deleteDelegation, arg.Cid, arg.DidID)
	return err
}

const deleteEnclave = `-- name: DeleteEnclave :exec
DELETE FROM mpc_enclaves WHERE id = ? AND did_id = ?
`

type DeleteEnclaveParams struct {
	ID    int64 `json:"id"`
	DidID int64 `json:"did_id"`
}

func (q *Queries) DeleteEnclave(ctx context.Context, arg DeleteEnclaveParams) error {
	_, err := q.db.ExecContext(ctx, deleteEnclave, arg.ID, arg.DidID)
	return err
}

const deleteExpiredSessions = `-- name: DeleteExpiredSessions :exec
DELETE FROM sessions WHERE expires_at < datetime('now')
`

func (q *Queries) DeleteExpiredSessions(ctx context.Context) error {
	_, err := q.db.ExecContext(ctx, deleteExpiredSessions)
	return err
}

const deleteSession = `-- name: DeleteSession :exec
DELETE FROM sessions WHERE id = ?
`

func (q *Queries) DeleteSession(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, deleteSession, id)
	return err
}

const deleteVerificationMethod = `-- name: DeleteVerificationMethod :exec
DELETE FROM verification_methods WHERE id = ?
`

func (q *Queries) DeleteVerificationMethod(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, deleteVerificationMethod, id)
	return err
}

const getAccountByAddress = `-- name: GetAccountByAddress :one
SELECT id, did_id, enclave_id, address, chain_id, coin_type, account_index, address_index, label, is_default, created_at FROM accounts WHERE address = ? LIMIT 1
`

func (q *Queries) GetAccountByAddress(ctx context.Context, address string) (Account, error) {
	row := q.db.QueryRowContext(ctx, getAccountByAddress, address)
	var i Account
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.EnclaveID,
		&i.Address,
		&i.ChainID,
		&i.CoinType,
		&i.AccountIndex,
		&i.AddressIndex,
		&i.Label,
		&i.IsDefault,
		&i.CreatedAt,
	)
	return i, err
}

const getCredentialByID = `-- name: GetCredentialByID :one
SELECT id, did_id, credential_id, public_key, public_key_alg, aaguid, sign_count, transports, device_name, device_type, authenticator, is_discoverable, backed_up, created_at, last_used FROM credentials WHERE credential_id = ? LIMIT 1
`

func (q *Queries) GetCredentialByID(ctx context.Context, credentialID string) (Credential, error) {
	row := q.db.QueryRowContext(ctx, getCredentialByID, credentialID)
	var i Credential
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.CredentialID,
		&i.PublicKey,
		&i.PublicKeyAlg,
		&i.Aaguid,
		&i.SignCount,
		&i.Transports,
		&i.DeviceName,
		&i.DeviceType,
		&i.Authenticator,
		&i.IsDiscoverable,
		&i.BackedUp,
		&i.CreatedAt,
		&i.LastUsed,
	)
	return i, err
}

const getCurrentSession = `-- name: GetCurrentSession :one
SELECT id, did_id, credential_id, session_id, device_info, is_current, last_activity, expires_at, created_at FROM sessions WHERE did_id = ? AND is_current = 1 LIMIT 1
`

func (q *Queries) GetCurrentSession(ctx context.Context, didID int64) (Session, error) {
	row := q.db.QueryRowContext(ctx, getCurrentSession, didID)
	var i Session
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.CredentialID,
		&i.SessionID,
		&i.DeviceInfo,
		&i.IsCurrent,
		&i.LastActivity,
		&i.ExpiresAt,
		&i.CreatedAt,
	)
	return i, err
}

const getDIDByDID = `-- name: GetDIDByDID :one

SELECT id, did, controller, document, sequence, last_synced, created_at, updated_at FROM did_documents WHERE did = ? LIMIT 1
`

// =============================================================================
// DID DOCUMENT QUERIES
// =============================================================================
func (q *Queries) GetDIDByDID(ctx context.Context, did string) (DidDocument, error) {
	row := q.db.QueryRowContext(ctx, getDIDByDID, did)
	var i DidDocument
	err := row.Scan(
		&i.ID,
		&i.Did,
		&i.Controller,
		&i.Document,
		&i.Sequence,
		&i.LastSynced,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getDIDByID = `-- name: GetDIDByID :one
SELECT id, did, controller, document, sequence, last_synced, created_at, updated_at FROM did_documents WHERE id = ? LIMIT 1
`

func (q *Queries) GetDIDByID(ctx context.Context, id int64) (DidDocument, error) {
	row := q.db.QueryRowContext(ctx, getDIDByID, id)
	var i DidDocument
	err := row.Scan(
		&i.ID,
		&i.Did,
		&i.Controller,
		&i.Document,
		&i.Sequence,
		&i.LastSynced,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getDefaultAccount = `-- name: GetDefaultAccount :one
SELECT id, did_id, enclave_id, address, chain_id, coin_type, account_index, address_index, label, is_default, created_at FROM accounts WHERE did_id = ? AND chain_id = ? AND is_default = 1 LIMIT 1
`

type GetDefaultAccountParams struct {
	DidID   int64  `json:"did_id"`
	ChainID string `json:"chain_id"`
}

func (q *Queries) GetDefaultAccount(ctx context.Context, arg GetDefaultAccountParams) (Account, error) {
	row := q.db.QueryRowContext(ctx, getDefaultAccount, arg.DidID, arg.ChainID)
	var i Account
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.EnclaveID,
		&i.Address,
		&i.ChainID,
		&i.CoinType,
		&i.AccountIndex,
		&i.AddressIndex,
		&i.Label,
		&i.IsDefault,
		&i.CreatedAt,
	)
	return i, err
}

const getDelegationByCID = `-- name: GetDelegationByCID :one

SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations WHERE cid = ? LIMIT 1
`

// =============================================================================
// UCAN DELEGATION QUERIES (v1.0.0-rc.1)
// =============================================================================
func (q *Queries) GetDelegationByCID(ctx context.Context, cid string) (UcanDelegation, error) {
	row := q.db.QueryRowContext(ctx, getDelegationByCID, cid)
	var i UcanDelegation
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.Cid,
		&i.Envelope,
		&i.Iss,
		&i.Aud,
		&i.Sub,
		&i.Cmd,
		&i.Pol,
		&i.Nbf,
		&i.Exp,
		&i.IsRoot,
		&i.IsPowerline,
		&i.CreatedAt,
	)
	return i, err
}

const getDelegationEnvelopeByCID = `-- name: GetDelegationEnvelopeByCID :one
SELECT envelope FROM ucan_delegations WHERE cid = ? LIMIT 1
`

func (q *Queries) GetDelegationEnvelopeByCID(ctx context.Context, cid string) ([]byte, error) {
	row := q.db.QueryRowContext(ctx, getDelegationEnvelopeByCID, cid)
	var envelope []byte
	err := row.Scan(&envelope)
	return envelope, err
}

const getEnclaveByID = `-- name: GetEnclaveByID :one
SELECT id, did_id, enclave_id, public_key_hex, public_key, val_share, user_share, nonce, curve, status, created_at, rotated_at FROM mpc_enclaves WHERE enclave_id = ? LIMIT 1
`

func (q *Queries) GetEnclaveByID(ctx context.Context, enclaveID string) (MpcEnclafe, error) {
	row := q.db.QueryRowContext(ctx, getEnclaveByID, enclaveID)
	var i MpcEnclafe
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.EnclaveID,
		&i.PublicKeyHex,
		&i.PublicKey,
		&i.ValShare,
		&i.UserShare,
		&i.Nonce,
		&i.Curve,
		&i.Status,
		&i.CreatedAt,
		&i.RotatedAt,
	)
	return i, err
}

const getEnclaveByPubKeyHex = `-- name: GetEnclaveByPubKeyHex :one
SELECT id, did_id, enclave_id, public_key_hex, public_key, val_share, user_share, nonce, curve, status, created_at, rotated_at FROM mpc_enclaves WHERE public_key_hex = ? LIMIT 1
`

func (q *Queries) GetEnclaveByPubKeyHex(ctx context.Context, publicKeyHex string) (MpcEnclafe, error) {
	row := q.db.QueryRowContext(ctx, getEnclaveByPubKeyHex, publicKeyHex)
	var i MpcEnclafe
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.EnclaveID,
		&i.PublicKeyHex,
		&i.PublicKey,
		&i.ValShare,
		&i.UserShare,
		&i.Nonce,
		&i.Curve,
		&i.Status,
		&i.CreatedAt,
		&i.RotatedAt,
	)
	return i, err
}

const getGrantByService = `-- name: GetGrantByService :one
SELECT id, did_id, service_id, delegation_cid, scopes, accounts, status, granted_at, last_used, expires_at FROM grants WHERE did_id = ? AND service_id = ? LIMIT 1
`

type GetGrantByServiceParams struct {
	DidID     int64 `json:"did_id"`
	ServiceID int64 `json:"service_id"`
}

func (q *Queries) GetGrantByService(ctx context.Context, arg GetGrantByServiceParams) (Grant, error) {
	row := q.db.QueryRowContext(ctx, getGrantByService, arg.DidID, arg.ServiceID)
	var i Grant
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.ServiceID,
		&i.DelegationCid,
		&i.Scopes,
		&i.Accounts,
		&i.Status,
		&i.GrantedAt,
		&i.LastUsed,
		&i.ExpiresAt,
	)
	return i, err
}

const getInvocationByCID = `-- name: GetInvocationByCID :one

SELECT id, did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat, executed_at, result_cid, created_at FROM ucan_invocations WHERE cid = ? LIMIT 1
`

// =============================================================================
// UCAN INVOCATION QUERIES (v1.0.0-rc.1)
// =============================================================================
func (q *Queries) GetInvocationByCID(ctx context.Context, cid string) (UcanInvocation, error) {
	row := q.db.QueryRowContext(ctx, getInvocationByCID, cid)
	var i UcanInvocation
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.Cid,
		&i.Envelope,
		&i.Iss,
		&i.Sub,
		&i.Aud,
		&i.Cmd,
		&i.Prf,
		&i.Exp,
		&i.Iat,
		&i.ExecutedAt,
		&i.ResultCid,
		&i.CreatedAt,
	)
	return i, err
}

const getInvocationEnvelopeByCID = `-- name: GetInvocationEnvelopeByCID :one
SELECT envelope FROM ucan_invocations WHERE cid = ? LIMIT 1
`

func (q *Queries) GetInvocationEnvelopeByCID(ctx context.Context, cid string) ([]byte, error) {
	row := q.db.QueryRowContext(ctx, getInvocationEnvelopeByCID, cid)
	var envelope []byte
	err := row.Scan(&envelope)
	return envelope, err
}

const getRevocation = `-- name: GetRevocation :one
SELECT id, delegation_cid, revoked_by, invocation_cid, reason, revoked_at FROM ucan_revocations WHERE delegation_cid = ? LIMIT 1
`

func (q *Queries) GetRevocation(ctx context.Context, delegationCid string) (UcanRevocation, error) {
	row := q.db.QueryRowContext(ctx, getRevocation, delegationCid)
	var i UcanRevocation
	err := row.Scan(
		&i.ID,
		&i.DelegationCid,
		&i.RevokedBy,
		&i.InvocationCid,
		&i.Reason,
		&i.RevokedAt,
	)
	return i, err
}

const getServiceByID = `-- name: GetServiceByID :one
SELECT id, origin, name, description, logo_url, did, is_verified, metadata, created_at FROM services WHERE id = ? LIMIT 1
`

func (q *Queries) GetServiceByID(ctx context.Context, id int64) (Service, error) {
	row := q.db.QueryRowContext(ctx, getServiceByID, id)
	var i Service
	err := row.Scan(
		&i.ID,
		&i.Origin,
		&i.Name,
		&i.Description,
		&i.LogoUrl,
		&i.Did,
		&i.IsVerified,
		&i.Metadata,
		&i.CreatedAt,
	)
	return i, err
}

const getServiceByOrigin = `-- name: GetServiceByOrigin :one

SELECT id, origin, name, description, logo_url, did, is_verified, metadata, created_at FROM services WHERE origin = ? LIMIT 1
`

// =============================================================================
// SERVICE QUERIES
// =============================================================================
func (q *Queries) GetServiceByOrigin(ctx context.Context, origin string) (Service, error) {
	row := q.db.QueryRowContext(ctx, getServiceByOrigin, origin)
	var i Service
	err := row.Scan(
		&i.ID,
		&i.Origin,
		&i.Name,
		&i.Description,
		&i.LogoUrl,
		&i.Did,
		&i.IsVerified,
		&i.Metadata,
		&i.CreatedAt,
	)
	return i, err
}

const getSessionByID = `-- name: GetSessionByID :one
SELECT id, did_id, credential_id, session_id, device_info, is_current, last_activity, expires_at, created_at FROM sessions WHERE session_id = ? LIMIT 1
`

func (q *Queries) GetSessionByID(ctx context.Context, sessionID string) (Session, error) {
	row := q.db.QueryRowContext(ctx, getSessionByID, sessionID)
	var i Session
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.CredentialID,
		&i.SessionID,
		&i.DeviceInfo,
		&i.IsCurrent,
		&i.LastActivity,
		&i.ExpiresAt,
		&i.CreatedAt,
	)
	return i, err
}

const getSyncCheckpoint = `-- name: GetSyncCheckpoint :one

SELECT id, did_id, resource_type, last_block, last_tx_hash, last_synced FROM sync_checkpoints WHERE did_id = ? AND resource_type = ? LIMIT 1
`

type GetSyncCheckpointParams struct {
	DidID        int64  `json:"did_id"`
	ResourceType string `json:"resource_type"`
}

// =============================================================================
// SYNC QUERIES
// =============================================================================
func (q *Queries) GetSyncCheckpoint(ctx context.Context, arg GetSyncCheckpointParams) (SyncCheckpoint, error) {
	row := q.db.QueryRowContext(ctx, getSyncCheckpoint, arg.DidID, arg.ResourceType)
	var i SyncCheckpoint
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.ResourceType,
		&i.LastBlock,
		&i.LastTxHash,
		&i.LastSynced,
	)
	return i, err
}

const getVerificationMethod = `-- name: GetVerificationMethod :one
SELECT id, did_id, method_id, method_type, controller, public_key, purpose, created_at FROM verification_methods WHERE did_id = ? AND method_id = ? LIMIT 1
`

type GetVerificationMethodParams struct {
	DidID    int64  `json:"did_id"`
	MethodID string `json:"method_id"`
}

func (q *Queries) GetVerificationMethod(ctx context.Context, arg GetVerificationMethodParams) (VerificationMethod, error) {
	row := q.db.QueryRowContext(ctx, getVerificationMethod, arg.DidID, arg.MethodID)
	var i VerificationMethod
	err := row.Scan(
		&i.ID,
		&i.DidID,
		&i.MethodID,
		&i.MethodType,
		&i.Controller,
		&i.PublicKey,
		&i.Purpose,
		&i.CreatedAt,
	)
	return i, err
}

const isDelegationRevoked = `-- name: IsDelegationRevoked :one
SELECT EXISTS(SELECT 1 FROM ucan_revocations WHERE delegation_cid = ?) as revoked
`

func (q *Queries) IsDelegationRevoked(ctx context.Context, delegationCid string) (int64, error) {
	row := q.db.QueryRowContext(ctx, isDelegationRevoked, delegationCid)
	var revoked int64
	err := row.Scan(&revoked)
	return revoked, err
}

const listAccountsByChain = `-- name: ListAccountsByChain :many
SELECT id, did_id, enclave_id, address, chain_id, coin_type, account_index, address_index, label, is_default, created_at FROM accounts WHERE did_id = ? AND chain_id = ? ORDER BY account_index, address_index
`

type ListAccountsByChainParams struct {
	DidID   int64  `json:"did_id"`
	ChainID string `json:"chain_id"`
}

func (q *Queries) ListAccountsByChain(ctx context.Context, arg ListAccountsByChainParams) ([]Account, error) {
	rows, err := q.db.QueryContext(ctx, listAccountsByChain, arg.DidID, arg.ChainID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []Account{}
	for rows.Next() {
		var i Account
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.EnclaveID,
			&i.Address,
			&i.ChainID,
			&i.CoinType,
			&i.AccountIndex,
			&i.AddressIndex,
			&i.Label,
			&i.IsDefault,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAccountsByDID = `-- name: ListAccountsByDID :many

SELECT id, did_id, enclave_id, address, chain_id, coin_type, account_index, address_index, label, is_default, created_at, public_key_hex, curve, enclave_ref FROM v_accounts WHERE did_id = ? ORDER BY is_default DESC, created_at
`

// =============================================================================
// ACCOUNT QUERIES
// =============================================================================
func (q *Queries) ListAccountsByDID(ctx context.Context, didID int64) ([]VAccount, error) {
	rows, err := q.db.QueryContext(ctx, listAccountsByDID, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []VAccount{}
	for rows.Next() {
		var i VAccount
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.EnclaveID,
			&i.Address,
			&i.ChainID,
			&i.CoinType,
			&i.AccountIndex,
			&i.AddressIndex,
			&i.Label,
			&i.IsDefault,
			&i.CreatedAt,
			&i.PublicKeyHex,
			&i.Curve,
			&i.EnclaveRef,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAllDIDs = `-- name: ListAllDIDs :many
SELECT id, did, controller, document, sequence, last_synced, created_at, updated_at FROM did_documents ORDER BY created_at DESC
`

func (q *Queries) ListAllDIDs(ctx context.Context) ([]DidDocument, error) {
	rows, err := q.db.QueryContext(ctx, listAllDIDs)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []DidDocument{}
	for rows.Next() {
		var i DidDocument
		if err := rows.Scan(
			&i.ID,
			&i.Did,
			&i.Controller,
			&i.Document,
			&i.Sequence,
			&i.LastSynced,
			&i.CreatedAt,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listCredentialsByDID = `-- name: ListCredentialsByDID :many

SELECT id, did_id, credential_id, public_key, public_key_alg, aaguid, sign_count, transports, device_name, device_type, authenticator, is_discoverable, backed_up, created_at, last_used FROM credentials WHERE did_id = ? ORDER BY last_used DESC
`

// =============================================================================
// CREDENTIAL QUERIES
// =============================================================================
func (q *Queries) ListCredentialsByDID(ctx context.Context, didID int64) ([]Credential, error) {
	rows, err := q.db.QueryContext(ctx, listCredentialsByDID, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []Credential{}
	for rows.Next() {
		var i Credential
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.CredentialID,
			&i.PublicKey,
			&i.PublicKeyAlg,
			&i.Aaguid,
			&i.SignCount,
			&i.Transports,
			&i.DeviceName,
			&i.DeviceType,
			&i.Authenticator,
			&i.IsDiscoverable,
			&i.BackedUp,
			&i.CreatedAt,
			&i.LastUsed,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDelegationsByAudience = `-- name: ListDelegationsByAudience :many
SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations 
WHERE aud = ? AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at DESC
`

func (q *Queries) ListDelegationsByAudience(ctx context.Context, aud string) ([]UcanDelegation, error) {
	rows, err := q.db.QueryContext(ctx, listDelegationsByAudience, aud)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanDelegation{}
	for rows.Next() {
		var i UcanDelegation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Aud,
			&i.Sub,
			&i.Cmd,
			&i.Pol,
			&i.Nbf,
			&i.Exp,
			&i.IsRoot,
			&i.IsPowerline,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDelegationsByDID = `-- name: ListDelegationsByDID :many
SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations 
WHERE did_id = ? AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at DESC
`

func (q *Queries) ListDelegationsByDID(ctx context.Context, didID int64) ([]UcanDelegation, error) {
	rows, err := q.db.QueryContext(ctx, listDelegationsByDID, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanDelegation{}
	for rows.Next() {
		var i UcanDelegation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Aud,
			&i.Sub,
			&i.Cmd,
			&i.Pol,
			&i.Nbf,
			&i.Exp,
			&i.IsRoot,
			&i.IsPowerline,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDelegationsByIssuer = `-- name: ListDelegationsByIssuer :many
SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations 
WHERE iss = ? AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at DESC
`

func (q *Queries) ListDelegationsByIssuer(ctx context.Context, iss string) ([]UcanDelegation, error) {
	rows, err := q.db.QueryContext(ctx, listDelegationsByIssuer, iss)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanDelegation{}
	for rows.Next() {
		var i UcanDelegation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Aud,
			&i.Sub,
			&i.Cmd,
			&i.Pol,
			&i.Nbf,
			&i.Exp,
			&i.IsRoot,
			&i.IsPowerline,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDelegationsBySubject = `-- name: ListDelegationsBySubject :many
SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations 
WHERE sub = ? AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at DESC
`

func (q *Queries) ListDelegationsBySubject(ctx context.Context, sub *string) ([]UcanDelegation, error) {
	rows, err := q.db.QueryContext(ctx, listDelegationsBySubject, sub)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanDelegation{}
	for rows.Next() {
		var i UcanDelegation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Aud,
			&i.Sub,
			&i.Cmd,
			&i.Pol,
			&i.Nbf,
			&i.Exp,
			&i.IsRoot,
			&i.IsPowerline,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDelegationsForCommand = `-- name: ListDelegationsForCommand :many
SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations 
WHERE did_id = ? 
  AND (cmd = ? OR cmd = '/' OR ? LIKE cmd || '/%')
  AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at DESC
`

type ListDelegationsForCommandParams struct {
	DidID int64  `json:"did_id"`
	Cmd   string `json:"cmd"`
	Cmd_2 string `json:"cmd_2"`
}

func (q *Queries) ListDelegationsForCommand(ctx context.Context, arg ListDelegationsForCommandParams) ([]UcanDelegation, error) {
	rows, err := q.db.QueryContext(ctx, listDelegationsForCommand, arg.DidID, arg.Cmd, arg.Cmd_2)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanDelegation{}
	for rows.Next() {
		var i UcanDelegation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Aud,
			&i.Sub,
			&i.Cmd,
			&i.Pol,
			&i.Nbf,
			&i.Exp,
			&i.IsRoot,
			&i.IsPowerline,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listEnclavesByDID = `-- name: ListEnclavesByDID :many

SELECT id, did_id, enclave_id, public_key_hex, public_key, val_share, user_share, nonce, curve, status, created_at, rotated_at FROM mpc_enclaves WHERE did_id = ? AND status = 'active' ORDER BY created_at
`

// =============================================================================
// MPC ENCLAVE QUERIES
// =============================================================================
func (q *Queries) ListEnclavesByDID(ctx context.Context, didID int64) ([]MpcEnclafe, error) {
	rows, err := q.db.QueryContext(ctx, listEnclavesByDID, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []MpcEnclafe{}
	for rows.Next() {
		var i MpcEnclafe
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.EnclaveID,
			&i.PublicKeyHex,
			&i.PublicKey,
			&i.ValShare,
			&i.UserShare,
			&i.Nonce,
			&i.Curve,
			&i.Status,
			&i.CreatedAt,
			&i.RotatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listGrantsByDID = `-- name: ListGrantsByDID :many

SELECT id, did_id, service_id, delegation_cid, scopes, accounts, status, granted_at, last_used, expires_at, service_name, service_origin, service_logo FROM v_grants WHERE did_id = ? AND status = 'active' ORDER BY last_used DESC NULLS LAST
`

// =============================================================================
// GRANT QUERIES
// =============================================================================
func (q *Queries) ListGrantsByDID(ctx context.Context, didID int64) ([]VGrant, error) {
	rows, err := q.db.QueryContext(ctx, listGrantsByDID, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []VGrant{}
	for rows.Next() {
		var i VGrant
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.ServiceID,
			&i.DelegationCid,
			&i.Scopes,
			&i.Accounts,
			&i.Status,
			&i.GrantedAt,
			&i.LastUsed,
			&i.ExpiresAt,
			&i.ServiceName,
			&i.ServiceOrigin,
			&i.ServiceLogo,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listInvocationsByDID = `-- name: ListInvocationsByDID :many
SELECT id, did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat, executed_at, result_cid, created_at FROM ucan_invocations 
WHERE did_id = ?
ORDER BY created_at DESC
LIMIT ?
`

type ListInvocationsByDIDParams struct {
	DidID int64 `json:"did_id"`
	Limit int64 `json:"limit"`
}

func (q *Queries) ListInvocationsByDID(ctx context.Context, arg ListInvocationsByDIDParams) ([]UcanInvocation, error) {
	rows, err := q.db.QueryContext(ctx, listInvocationsByDID, arg.DidID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanInvocation{}
	for rows.Next() {
		var i UcanInvocation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Sub,
			&i.Aud,
			&i.Cmd,
			&i.Prf,
			&i.Exp,
			&i.Iat,
			&i.ExecutedAt,
			&i.ResultCid,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listInvocationsByIssuer = `-- name: ListInvocationsByIssuer :many
SELECT id, did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat, executed_at, result_cid, created_at FROM ucan_invocations 
WHERE iss = ?
ORDER BY created_at DESC
LIMIT ?
`

type ListInvocationsByIssuerParams struct {
	Iss   string `json:"iss"`
	Limit int64  `json:"limit"`
}

func (q *Queries) ListInvocationsByIssuer(ctx context.Context, arg ListInvocationsByIssuerParams) ([]UcanInvocation, error) {
	rows, err := q.db.QueryContext(ctx, listInvocationsByIssuer, arg.Iss, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanInvocation{}
	for rows.Next() {
		var i UcanInvocation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Sub,
			&i.Aud,
			&i.Cmd,
			&i.Prf,
			&i.Exp,
			&i.Iat,
			&i.ExecutedAt,
			&i.ResultCid,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listInvocationsBySubject = `-- name: ListInvocationsBySubject :many
SELECT id, did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat, executed_at, result_cid, created_at FROM ucan_invocations 
WHERE sub = ?
ORDER BY created_at DESC
LIMIT ?
`

type ListInvocationsBySubjectParams struct {
	Sub   string `json:"sub"`
	Limit int64  `json:"limit"`
}

func (q *Queries) ListInvocationsBySubject(ctx context.Context, arg ListInvocationsBySubjectParams) ([]UcanInvocation, error) {
	rows, err := q.db.QueryContext(ctx, listInvocationsBySubject, arg.Sub, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanInvocation{}
	for rows.Next() {
		var i UcanInvocation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Sub,
			&i.Aud,
			&i.Cmd,
			&i.Prf,
			&i.Exp,
			&i.Iat,
			&i.ExecutedAt,
			&i.ResultCid,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listInvocationsForCommand = `-- name: ListInvocationsForCommand :many
SELECT id, did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat, executed_at, result_cid, created_at FROM ucan_invocations 
WHERE did_id = ? AND cmd = ?
ORDER BY created_at DESC
LIMIT ?
`

type ListInvocationsForCommandParams struct {
	DidID int64  `json:"did_id"`
	Cmd   string `json:"cmd"`
	Limit int64  `json:"limit"`
}

func (q *Queries) ListInvocationsForCommand(ctx context.Context, arg ListInvocationsForCommandParams) ([]UcanInvocation, error) {
	rows, err := q.db.QueryContext(ctx, listInvocationsForCommand, arg.DidID, arg.Cmd, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanInvocation{}
	for rows.Next() {
		var i UcanInvocation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Sub,
			&i.Aud,
			&i.Cmd,
			&i.Prf,
			&i.Exp,
			&i.Iat,
			&i.ExecutedAt,
			&i.ResultCid,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPendingInvocations = `-- name: ListPendingInvocations :many
SELECT id, did_id, cid, envelope, iss, sub, aud, cmd, prf, exp, iat, executed_at, result_cid, created_at FROM ucan_invocations 
WHERE did_id = ? AND executed_at IS NULL AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at ASC
`

func (q *Queries) ListPendingInvocations(ctx context.Context, didID int64) ([]UcanInvocation, error) {
	rows, err := q.db.QueryContext(ctx, listPendingInvocations, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanInvocation{}
	for rows.Next() {
		var i UcanInvocation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Sub,
			&i.Aud,
			&i.Cmd,
			&i.Prf,
			&i.Exp,
			&i.Iat,
			&i.ExecutedAt,
			&i.ResultCid,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPowerlineDelegations = `-- name: ListPowerlineDelegations :many
SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations 
WHERE did_id = ? AND is_powerline = 1 AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at DESC
`

func (q *Queries) ListPowerlineDelegations(ctx context.Context, didID int64) ([]UcanDelegation, error) {
	rows, err := q.db.QueryContext(ctx, listPowerlineDelegations, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanDelegation{}
	for rows.Next() {
		var i UcanDelegation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Aud,
			&i.Sub,
			&i.Cmd,
			&i.Pol,
			&i.Nbf,
			&i.Exp,
			&i.IsRoot,
			&i.IsPowerline,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRevocationsByRevoker = `-- name: ListRevocationsByRevoker :many
SELECT id, delegation_cid, revoked_by, invocation_cid, reason, revoked_at FROM ucan_revocations 
WHERE revoked_by = ?
ORDER BY revoked_at DESC
`

func (q *Queries) ListRevocationsByRevoker(ctx context.Context, revokedBy string) ([]UcanRevocation, error) {
	rows, err := q.db.QueryContext(ctx, listRevocationsByRevoker, revokedBy)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanRevocation{}
	for rows.Next() {
		var i UcanRevocation
		if err := rows.Scan(
			&i.ID,
			&i.DelegationCid,
			&i.RevokedBy,
			&i.InvocationCid,
			&i.Reason,
			&i.RevokedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRootDelegations = `-- name: ListRootDelegations :many
SELECT id, did_id, cid, envelope, iss, aud, sub, cmd, pol, nbf, exp, is_root, is_powerline, created_at FROM ucan_delegations 
WHERE did_id = ? AND is_root = 1 AND (exp IS NULL OR exp > datetime('now'))
ORDER BY created_at DESC
`

func (q *Queries) ListRootDelegations(ctx context.Context, didID int64) ([]UcanDelegation, error) {
	rows, err := q.db.QueryContext(ctx, listRootDelegations, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []UcanDelegation{}
	for rows.Next() {
		var i UcanDelegation
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.Cid,
			&i.Envelope,
			&i.Iss,
			&i.Aud,
			&i.Sub,
			&i.Cmd,
			&i.Pol,
			&i.Nbf,
			&i.Exp,
			&i.IsRoot,
			&i.IsPowerline,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSessionsByDID = `-- name: ListSessionsByDID :many

SELECT id, did_id, credential_id, session_id, device_info, is_current, last_activity, expires_at, created_at, device_name, authenticator FROM v_sessions WHERE did_id = ? ORDER BY last_activity DESC
`

// =============================================================================
// SESSION QUERIES
// =============================================================================
func (q *Queries) ListSessionsByDID(ctx context.Context, didID int64) ([]VSession, error) {
	rows, err := q.db.QueryContext(ctx, listSessionsByDID, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []VSession{}
	for rows.Next() {
		var i VSession
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.CredentialID,
			&i.SessionID,
			&i.DeviceInfo,
			&i.IsCurrent,
			&i.LastActivity,
			&i.ExpiresAt,
			&i.CreatedAt,
			&i.DeviceName,
			&i.Authenticator,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSyncCheckpoints = `-- name: ListSyncCheckpoints :many
SELECT id, did_id, resource_type, last_block, last_tx_hash, last_synced FROM sync_checkpoints WHERE did_id = ?
`

func (q *Queries) ListSyncCheckpoints(ctx context.Context, didID int64) ([]SyncCheckpoint, error) {
	rows, err := q.db.QueryContext(ctx, listSyncCheckpoints, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []SyncCheckpoint{}
	for rows.Next() {
		var i SyncCheckpoint
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.ResourceType,
			&i.LastBlock,
			&i.LastTxHash,
			&i.LastSynced,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVerificationMethods = `-- name: ListVerificationMethods :many

SELECT id, did_id, method_id, method_type, controller, public_key, purpose, created_at FROM verification_methods WHERE did_id = ? ORDER BY created_at
`

// =============================================================================
// VERIFICATION METHOD QUERIES
// =============================================================================
func (q *Queries) ListVerificationMethods(ctx context.Context, didID int64) ([]VerificationMethod, error) {
	rows, err := q.db.QueryContext(ctx, listVerificationMethods, didID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []VerificationMethod{}
	for rows.Next() {
		var i VerificationMethod
		if err := rows.Scan(
			&i.ID,
			&i.DidID,
			&i.MethodID,
			&i.MethodType,
			&i.Controller,
			&i.PublicKey,
			&i.Purpose,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVerifiedServices = `-- name: ListVerifiedServices :many
SELECT id, origin, name, description, logo_url, did, is_verified, metadata, created_at FROM services WHERE is_verified = 1 ORDER BY name
`

func (q *Queries) ListVerifiedServices(ctx context.Context) ([]Service, error) {
	rows, err := q.db.QueryContext(ctx, listVerifiedServices)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []Service{}
	for rows.Next() {
		var i Service
		if err := rows.Scan(
			&i.ID,
			&i.Origin,
			&i.Name,
			&i.Description,
			&i.LogoUrl,
			&i.Did,
			&i.IsVerified,
			&i.Metadata,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const markInvocationExecuted = `-- name: MarkInvocationExecuted :exec
UPDATE ucan_invocations 
SET executed_at = datetime('now'), result_cid = ?
WHERE cid = ?
`

type MarkInvocationExecutedParams struct {
	ResultCid *string `json:"result_cid"`
	Cid       string  `json:"cid"`
}

func (q *Queries) MarkInvocationExecuted(ctx context.Context, arg MarkInvocationExecutedParams) error {
	_, err := q.db.ExecContext(ctx, markInvocationExecuted, arg.ResultCid, arg.Cid)
	return err
}

const reactivateGrant = `-- name: ReactivateGrant :exec
UPDATE grants SET status = 'active' WHERE id = ? AND status = 'suspended'
`

func (q *Queries) ReactivateGrant(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, reactivateGrant, id)
	return err
}

const renameCredential = `-- name: RenameCredential :exec
UPDATE credentials SET device_name = ? WHERE id = ?
`

type RenameCredentialParams struct {
	DeviceName string `json:"device_name"`
	ID         int64  `json:"id"`
}

func (q *Queries) RenameCredential(ctx context.Context, arg RenameCredentialParams) error {
	_, err := q.db.ExecContext(ctx, renameCredential, arg.DeviceName, arg.ID)
	return err
}

const revokeGrant = `-- name: RevokeGrant :exec
UPDATE grants SET status = 'revoked' WHERE id = ?
`

func (q *Queries) RevokeGrant(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, revokeGrant, id)
	return err
}

const rotateEnclave = `-- name: RotateEnclave :exec
UPDATE mpc_enclaves 
SET status = 'rotating', rotated_at = datetime('now')
WHERE id = ?
`

func (q *Queries) RotateEnclave(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, rotateEnclave, id)
	return err
}

const setCurrentSession = `-- name: SetCurrentSession :exec
UPDATE sessions 
SET is_current = CASE WHEN id = ? THEN 1 ELSE 0 END 
WHERE did_id = ?
`

type SetCurrentSessionParams struct {
	ID    int64 `json:"id"`
	DidID int64 `json:"did_id"`
}

func (q *Queries) SetCurrentSession(ctx context.Context, arg SetCurrentSessionParams) error {
	_, err := q.db.ExecContext(ctx, setCurrentSession, arg.ID, arg.DidID)
	return err
}

const setDefaultAccount = `-- name: SetDefaultAccount :exec
UPDATE accounts 
SET is_default = CASE WHEN id = ? THEN 1 ELSE 0 END 
WHERE did_id = ? AND chain_id = ?
`

type SetDefaultAccountParams struct {
	ID      int64  `json:"id"`
	DidID   int64  `json:"did_id"`
	ChainID string `json:"chain_id"`
}

func (q *Queries) SetDefaultAccount(ctx context.Context, arg SetDefaultAccountParams) error {
	_, err := q.db.ExecContext(ctx, setDefaultAccount, arg.ID, arg.DidID, arg.ChainID)
	return err
}

const suspendGrant = `-- name: SuspendGrant :exec
UPDATE grants SET status = 'suspended' WHERE id = ?
`

func (q *Queries) SuspendGrant(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, suspendGrant, id)
	return err
}

const updateAccountLabel = `-- name: UpdateAccountLabel :exec
UPDATE accounts SET label = ? WHERE id = ?
`

type UpdateAccountLabelParams struct {
	Label *string `json:"label"`
	ID    int64   `json:"id"`
}

func (q *Queries) UpdateAccountLabel(ctx context.Context, arg UpdateAccountLabelParams) error {
	_, err := q.db.ExecContext(ctx, updateAccountLabel, arg.Label, arg.ID)
	return err
}

const updateCredentialCounter = `-- name: UpdateCredentialCounter :exec
UPDATE credentials 
SET sign_count = ?, last_used = datetime('now')
WHERE id = ?
`

type UpdateCredentialCounterParams struct {
	SignCount int64 `json:"sign_count"`
	ID        int64 `json:"id"`
}

func (q *Queries) UpdateCredentialCounter(ctx context.Context, arg UpdateCredentialCounterParams) error {
	_, err := q.db.ExecContext(ctx, updateCredentialCounter, arg.SignCount, arg.ID)
	return err
}

const updateDIDDocument = `-- name: UpdateDIDDocument :exec
UPDATE did_documents 
SET document = ?, sequence = ?, last_synced = datetime('now')
WHERE id = ?
`

type UpdateDIDDocumentParams struct {
	Document json.RawMessage `json:"document"`
	Sequence int64           `json:"sequence"`
	ID       int64           `json:"id"`
}

func (q *Queries) UpdateDIDDocument(ctx context.Context, arg UpdateDIDDocumentParams) error {
	_, err := q.db.ExecContext(ctx, updateDIDDocument, arg.Document, arg.Sequence, arg.ID)
	return err
}

const updateGrantLastUsed = `-- name: UpdateGrantLastUsed :exec
UPDATE grants SET last_used = datetime('now') WHERE id = ?
`

func (q *Queries) UpdateGrantLastUsed(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, updateGrantLastUsed, id)
	return err
}

const updateGrantScopes = `-- name: UpdateGrantScopes :exec
UPDATE grants SET scopes = ?, accounts = ? WHERE id = ?
`

type UpdateGrantScopesParams struct {
	Scopes   json.RawMessage `json:"scopes"`
	Accounts json.RawMessage `json:"accounts"`
	ID       int64           `json:"id"`
}

func (q *Queries) UpdateGrantScopes(ctx context.Context, arg UpdateGrantScopesParams) error {
	_, err := q.db.ExecContext(ctx, updateGrantScopes, arg.Scopes, arg.Accounts, arg.ID)
	return err
}

const updateService = `-- name: UpdateService :exec
UPDATE services 
SET name = ?, description = ?, logo_url = ?, metadata = ?
WHERE id = ?
`

type UpdateServiceParams struct {
	Name        string          `json:"name"`
	Description *string         `json:"description"`
	LogoUrl     *string         `json:"logo_url"`
	Metadata    json.RawMessage `json:"metadata"`
	ID          int64           `json:"id"`
}

func (q *Queries) UpdateService(ctx context.Context, arg UpdateServiceParams) error {
	_, err := q.db.ExecContext(ctx, updateService,
		arg.Name,
		arg.Description,
		arg.LogoUrl,
		arg.Metadata,
		arg.ID,
	)
	return err
}

const updateSessionActivity = `-- name: UpdateSessionActivity :exec
UPDATE sessions SET last_activity = datetime('now') WHERE id = ?
`

func (q *Queries) UpdateSessionActivity(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, updateSessionActivity, id)
	return err
}

const upsertSyncCheckpoint = `-- name: UpsertSyncCheckpoint :exec
INSERT INTO sync_checkpoints (did_id, resource_type, last_block, last_tx_hash)
VALUES (?, ?, ?, ?)
ON CONFLICT(did_id, resource_type) DO UPDATE SET
    last_block = excluded.last_block,
    last_tx_hash = excluded.last_tx_hash,
    last_synced = datetime('now')
`

type UpsertSyncCheckpointParams struct {
	DidID        int64   `json:"did_id"`
	ResourceType string  `json:"resource_type"`
	LastBlock    int64   `json:"last_block"`
	LastTxHash   *string `json:"last_tx_hash"`
}

func (q *Queries) UpsertSyncCheckpoint(ctx context.Context, arg UpsertSyncCheckpointParams) error {
	_, err := q.db.ExecContext(ctx, upsertSyncCheckpoint,
		arg.DidID,
		arg.ResourceType,
		arg.LastBlock,
		arg.LastTxHash,
	)
	return err
}
