import { default as joi } from 'joi';
import type { Knex } from 'knex';
import type { Lock } from '@verrou/core';
import type { Serializable } from '@nhtio/serialization/types';
import type { ConnectionStatus, KyooConfigurationOptions } from '.';
import type { KyooConnectionToAdapterBus } from '../utils/connection_to_adapter_bus';
import type { KyooJob, KyooJobToEnqueue, KyooWorkable } from '../job';
type KnexConfigKeysToIgnore = 'client' | 'dialect' | 'migrations' | 'postProcessResponse' | 'wrapIdentifier' | 'seeds' | 'useNullAsDefault' | 'searchPath' | 'asyncStackTraces' | 'compileSqlOnError' | 'fetchAsString' | 'log' | 'pool';
type KnexPoolConfigKeysToIgnore = 'afterCreate' | 'log' | 'propagateCreateError';
/**
 * Defines the settings for the database connection pool, controlling how many connections can be opened, reused, and managed concurrently.
 * This type is a subset of the Knex PoolConfig type, excluding keys that are not relevant for the SQL Adapter.
 * @prop name - The name of the pool, used for debugging purposes.
 * @prop min - The minimum number of connections to maintain in the pool.
 * @prop max - The maximum number of connections to maintain in the pool.
 * @prop refreshIdle - The time in milliseconds after which idle connections are refreshed.
 * @prop idleTimeoutMillis - The time in milliseconds after which idle connections are closed.
 * @prop reapIntervalMillis - The time in milliseconds after which idle connections are reaped.
 * @prop returnToHead - Whether to return idle connections to the head of the pool.
 * @prop priorityRange - Sets the number of priority levels available for connection requests; priorities range from 0 (highest) up to priorityRange - 1 (lowest).
 * @prop acquireTimeoutMillis - The maximum time in milliseconds to wait for a connection to be acquired from the pool before timing out.
 * @prop createRetryIntervalMillis - The time in milliseconds to wait before retrying to create a new connection when the pool is at maximum capacity.
 * @prop createTimeoutMillis - The maximum time in milliseconds to wait for a new connection to be created before timing out.
 * @prop destroyTimeoutMillis - The maximum time in milliseconds to wait for a connection to be destroyed before timing out.
 *
 * @interface
 */
export type PoolConfig = Omit<Knex.PoolConfig, KnexPoolConfigKeysToIgnore>;
/**
 * The KnexSQLClient type represents the Knex Client type, which is used to interact
 * with SQL databases in a type-safe manner.
 */
export type KnexSQLClient = typeof Knex.Client;
/**
 * The SQL Adapter is a Kyoo adapter that uses SQL databases to store and manage jobs.
 * See {@link KnexSQLClient} for more details on the shape of an SQL client class provided in the runtime.
 */
export type SQLClient = 'pg' | 'pg-native' | 'sqlite3' | 'better-sqlite3' | 'mysql' | 'mysql2' | 'oracledb' | 'tedious' | KnexSQLClient;
/**
 * Configuration schema for the SQL Adapter.
 *
 * This schema is similar to the Knex configuration schema, but with some additional fields specific to the SQL Adapter,
 * and omitting some fields which could cause issues with the SQL Adapter.
 *
 * @prop debug - Enables debug mode for the adapter, causing all queries to be logged and async stack traces to be captured for easier troubleshooting.
 * @prop client - The database client to use, such as 'pg' for PostgreSQL, 'mysql2' for MySQL, etc.
 * @prop jsonbSupport - Whether to use JSONB support for PostgreSQL databases. If set to `true`, the adapter will use JSONB columns for storing job data, which can improve performance and reduce storage space.
 * @prop version - Specifies the database version or dialect variant to help Knex adjust its SQL generation and feature support when using non-standard or version-sensitive clients.
 * @prop connection - The connection configuration for the database. This can be a connection string or an object with connection parameters.
 * @prop pool - Defines the settings for the database connection pool, controlling how many connections can be opened, reused, and managed concurrently.
 * @prop acquireConnectionTimeout - The maximum time in milliseconds to wait for a connection to be acquired from the pool before timing out.
 * @prop schema - The schema to use for the SQL Adapter tables. If not specified, it defaults to the default setting of the database driver.
 * @prop tablePrefix - The prefix to use for the SQL Adapter tables. This is useful for avoiding table name collisions in shared databases. If not specified, it defaults to `kyoo_`.
 * @prop enforceEnqueueSequence - Whether to enforce the sequence of job enqueueing. If set to `true`, jobs will be enqueued in the order they are provided. Defaults to `false`.
 * @prop migrate - Enable or disable automatic schema migrations at startup. Defaults to `true`.
 * @prop maxBulkInsertRows - Controls how many jobs can be attempted in a single insert statement (i.e., one SQL statement with multiple rows). Defaults to `1000`.
 * @prop maxIndividualInsertConcurrency - Controls how many single row inserts can be performed in parallel when falling back to per-job insertion. Defaults to `10`.
 * @prop lockAcquisitionConcurrency - Controls how many locks can be acquired in parallel when acquiring locks for job processing. Defaults to `100`.
 *
 * @interface
 */
export type SQLAdapterConfiguration = Omit<Knex.Config, KnexConfigKeysToIgnore> & {
    client?: SQLClient;
    schema?: string;
    tablePrefix?: string;
    enforceEnqueueSequence?: boolean;
    pool?: PoolConfig;
    migrate?: boolean;
    maxBulkInsertRows?: number;
    maxIndividualInsertConcurrency?: number;
    lockAcquisitionConcurrency?: number;
};
export declare const sqlAdapterConfigurationSchema: joi.ObjectSchema<SQLAdapterConfiguration>;
/**
 * Sanitizes a Knex configuration object for use with Kyoo.
 * @param obj The Knex configuration object to sanitize.
 * @param overrides Optional overrides to apply to the sanitized configuration.
 * @returns A sanitized version of the Knex configuration object, suitable for use with Kyoo.
 */
export declare const sanitizeKnexConfigForKyoo: (obj: Knex.Config, overrides?: SQLAdapterConfiguration) => SQLAdapterConfiguration;
/**
 * A type representing the public migration methods available on a Knex Migrator, but with all methods as zero-argument functions returning the same type as the original.
 * This omits the 'make' method, which is internal to Knex.
 *
 * The methods are:
 * - latest: Run all pending migrations.
 * - rollback: Roll back the last batch of migrations.
 * - status: Get the current migration status (number of migrations run or a status code).
 * - currentVersion: Get the current migration version (as a string or number).
 * - list: List all completed and pending migrations.
 * - up: Run the next migration that has not yet been run.
 * - down: Roll back the last migration that was run.
 * - forceFreeMigrationsLock: Force release the migration lock if stuck.
 */
export interface SQLAdapterMigatorType {
    /**
     * Run all pending migrations.
     * Equivalent to `knex.migrate.latest()`.
     */
    latest: () => ReturnType<Knex.Migrator['latest']>;
    /**
     * Roll back the last batch of migrations.
     * Equivalent to `knex.migrate.rollback()`.
     */
    rollback: () => ReturnType<Knex.Migrator['rollback']>;
    /**
     * Get the current migration status (number of migrations run or a status code).
     * Equivalent to `knex.migrate.status()`.
     */
    status: () => ReturnType<Knex.Migrator['status']>;
    /**
     * Get the current migration version (as a string or number).
     * Equivalent to `knex.migrate.currentVersion()`.
     */
    currentVersion: () => ReturnType<Knex.Migrator['currentVersion']>;
    /**
     * List all completed and pending migrations.
     * Equivalent to `knex.migrate.list()`.
     */
    list: () => ReturnType<Knex.Migrator['list']>;
    /**
     * Run the next migration that has not yet been run.
     * Equivalent to `knex.migrate.up()`.
     */
    up: () => ReturnType<Knex.Migrator['up']>;
    /**
     * Roll back the last migration that was run.
     * Equivalent to `knex.migrate.down()`.
     */
    down: () => ReturnType<Knex.Migrator['down']>;
    /**
     * Force release the migration lock if stuck.
     * Equivalent to `knex.migrate.forceFreeMigrationsLock()`.
     */
    forceFreeMigrationsLock: () => ReturnType<Knex.Migrator['forceFreeMigrationsLock']>;
}
/**
 * A class that wraps Knex's migration API for use with Kyoo's SQL adapter, providing a consistent interface for running and managing migrations.
 *
 * @example
 * const migrator = getSqlAdapterMigrator(config)
 * await migrator.latest()
 */
export declare class SQLAdapterMigrator implements SQLAdapterMigatorType {
    #private;
    /** @private */
    constructor(config: SQLAdapterConfiguration);
    /**
     * Run all pending migrations.
     * Equivalent to `knex.migrate.latest()`.
     */
    latest(): Promise<any>;
    /**
     * Roll back the last batch of migrations.
     * Equivalent to `knex.migrate.rollback()`.
     */
    rollback(): Promise<any>;
    /**
     * Get the current migration status (number of migrations run or a status code).
     * Equivalent to `knex.migrate.status()`.
     */
    status(): Promise<number>;
    /**
     * Get the current migration version (as a string or number).
     * Equivalent to `knex.migrate.currentVersion()`.
     */
    currentVersion(): Promise<string>;
    /**
     * List all completed and pending migrations.
     * Equivalent to `knex.migrate.list()`.
     */
    list(): Promise<any>;
    /**
     * Run the next migration that has not yet been run.
     * Equivalent to `knex.migrate.up()`.
     */
    up(): Promise<any>;
    /**
     * Roll back the last migration that was run.
     * Equivalent to `knex.migrate.down()`.
     */
    down(): Promise<any>;
    /**
     * Force release the migration lock if stuck.
     * Equivalent to `knex.migrate.forceFreeMigrationsLock()`.
     */
    forceFreeMigrationsLock(): Promise<any>;
    /**
     * Shuts down (destroys) the Knex instance underlying the migrator instance.
     * @warning If an error occurs during shutdown by knex or one if its underlying libraries, it will be thrown
     */
    shutdown(): Promise<void>;
}
/**
 * Validates and constructs a SQLAdapterMigrator instance from a configuration object.
 * Throws a KyooInvalidConfigurationError if the configuration is invalid.
 *
 * @param config - The configuration object to validate and use for the migrator.
 * @returns An instance of SQLAdapterMigrator ready for use.
 */
export declare const getSqlAdapterMigrator: (config: unknown) => SQLAdapterMigrator;
export declare class SQLAdapterLockManager {
    #private;
    /** @private */
    constructor(config: SQLAdapterConfiguration);
    getLockForQueueJobOperation(queue: string, jobId: string): Lock;
    getLockForQueueManagementOperation(queue: string): Lock;
    assertCanPerformQueueOperation(queue: string, operation: string): Promise<void>;
    purgeQueueJobLocks(queue: string): Promise<void>;
    purgeQueueManagementLocks(queue: string): Promise<void>;
    /**
     * Shuts down (destroys) the Knex instance underlying the migrator instance.
     * @warning If an error occurs during shutdown by knex or one if its underlying libraries, it will be thrown
     */
    shutdown(): Promise<void>;
}
export declare const getSqlAdapterLockManager: (config: unknown) => SQLAdapterLockManager;
export declare class SQLAdapter {
    #private;
    constructor(configuration: SQLAdapterConfiguration, bus: KyooConnectionToAdapterBus, options: KyooConfigurationOptions);
    connect(_signal?: AbortSignal): Promise<boolean>;
    disconnect(terminate?: boolean): Promise<void>;
    get connectionStatus(): ConnectionStatus;
    get queues(): any;
    get jobs(): {
        enqueue: (queue: string, ...jobs: KyooJobToEnqueue[]) => Promise<boolean | boolean[]>;
        purge: (queue: string) => Promise<void>;
        next: <T = Serializable>(queue: string, _noAck?: boolean, _rejectable?: boolean, onDispositioned?: (disposition: "ack" | "nack") => void) => Promise<KyooWorkable<T> | undefined>;
        enqueued: (queue: string) => Promise<number>;
        fetch: <T = Serializable>(queue: string, count: number) => Promise<Array<KyooJob<T>>>;
    };
}
export {};
