/**
 * GDPR Data Export Service
 *
 * Provides GDPR-compliant data export functionality for the INTENT module.
 * Supports right to access (data export) and right to erasure (soft delete).
 *
 * @packageDocumentation
 */
import { Queue } from 'bullmq';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type { Redis } from 'ioredis';
import { type Config } from '../common/config.js';
import { type AuditService } from '../audit/index.js';
import type { ID } from '../common/types.js';
/**
 * User roles that can perform GDPR operations
 */
export type GdprRole = 'admin' | 'tenant:admin' | 'dpo' | 'gdpr:admin' | 'user';
/**
 * GDPR authorization context - MUST be provided for all GDPR operations.
 * This context is constructed from the JWT token in the API layer.
 */
export interface GdprAuthorizationContext {
    /** The ID of the user making the request (from JWT sub claim) */
    requestingUserId: ID;
    /** The tenant ID of the requesting user (from JWT tenantId claim) */
    requestingUserTenantId: ID;
    /** The roles of the requesting user (from JWT roles claim) */
    roles: GdprRole[];
    /** IP address of the request for audit logging */
    ipAddress?: string;
    /** Request ID for correlation */
    requestId?: string;
    /** For erasure operations: whether explicit consent was provided */
    hasExplicitConsent?: boolean;
}
/**
 * Result of an authorization check
 */
export interface GdprAuthorizationResult {
    /** Whether the operation is authorized */
    authorized: boolean;
    /** Reason for the authorization decision */
    reason: string;
    /** The specific permission that granted access (if authorized) */
    grantedBy?: 'self' | 'admin' | 'dpo' | 'tenant_admin' | 'gdpr_admin';
}
/**
 * Dependencies for GdprService
 *
 * Use these to inject dependencies for testing or custom configurations.
 * If not provided, defaults to global singletons for backward compatibility.
 */
export interface GdprServiceDependencies {
    /** Drizzle database instance */
    database?: NodePgDatabase;
    /** Redis client instance */
    redis?: Redis;
    /** Application configuration */
    config?: Config;
    /** Audit service instance */
    auditService?: AuditService;
}
export type GdprExportStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'expired';
export interface GdprExportRequest {
    id: ID;
    userId: ID;
    tenantId: ID;
    status: GdprExportStatus;
    requestedAt: string;
    completedAt?: string;
    expiresAt?: string;
    downloadUrl?: string;
    error?: string;
    metadata?: Record<string, unknown>;
}
export interface GdprExportData {
    exportId: ID;
    userId: ID;
    tenantId: ID;
    exportTimestamp: string;
    dataCategories: string[];
    retentionPeriods: Record<string, string>;
    data: {
        intents: GdprIntentData[];
        events: GdprEventData[];
        escalations: GdprEscalationData[];
        auditRecords: GdprAuditData[];
    };
    metadata: {
        totalRecords: number;
        exportVersion: string;
        gdprArticle: string;
    };
}
export interface GdprIntentData {
    id: ID;
    goal: string;
    intentType: string | null;
    status: string;
    context: Record<string, unknown>;
    metadata: Record<string, unknown>;
    createdAt: string;
    updatedAt: string;
    deletedAt?: string | null;
}
export interface GdprEventData {
    id: ID;
    intentId: ID;
    eventType: string;
    payload: Record<string, unknown>;
    occurredAt: string;
}
export interface GdprEscalationData {
    id: ID;
    intentId: ID;
    reason: string;
    reasonCategory: string;
    escalatedTo: string;
    status: string;
    createdAt: string;
    resolvedAt?: string | null;
}
export interface GdprAuditData {
    id: ID;
    eventType: string;
    action: string;
    outcome: string;
    eventTime: string;
    metadata?: Record<string, unknown>;
}
export interface GdprErasureResult {
    userId: ID;
    tenantId: ID;
    erasedAt: string;
    counts: {
        intents: number;
        events: number;
        escalations: number;
    };
}
/**
 * GDPR Service for data export and erasure
 */
export declare class GdprService {
    private db;
    private redis;
    private config;
    private auditService;
    private auditHelper;
    private readonly cachePrefix;
    private readonly exportTtlSeconds;
    /**
     * Create a new GdprService instance.
     *
     * @param deps - Optional dependencies for dependency injection.
     *               If not provided, uses global singletons (backward compatible).
     *
     * @example
     * // Default usage (backward compatible)
     * const service = new GdprService();
     *
     * @example
     * // With dependency injection (for testing)
     * const service = new GdprService({
     *   database: mockDb,
     *   redis: mockRedis,
     *   config: testConfig,
     *   auditService: mockAuditService,
     * });
     */
    constructor(deps?: GdprServiceDependencies);
    /**
     * Record an authorization decision in the audit log.
     * This is critical for GDPR compliance and security monitoring.
     *
     * @param authContext - The authorization context
     * @param operation - The GDPR operation being performed
     * @param targetUserId - The user whose data is being accessed
     * @param targetTenantId - The tenant context
     * @param result - The authorization result
     */
    private recordAuthorizationDecision;
    /**
     * Enforce authorization for a GDPR operation.
     * Throws ForbiddenError if not authorized.
     *
     * @param authContext - The authorization context
     * @param operation - The GDPR operation
     * @param targetUserId - The target user ID
     * @param targetTenantId - The target tenant ID
     * @param checkFn - The authorization check function to use
     */
    private enforceAuthorization;
    /**
     * Export all user data for GDPR compliance (Article 15 - Right of Access)
     * Uses extended statement timeout for complex multi-table queries.
     * Protected by circuit breaker to prevent cascading failures.
     *
     * REQUIRES: GdprAuthorizationContext must be provided and valid.
     *
     * @param authContext - Authorization context from JWT (REQUIRED)
     * @param userId - The user/entity ID to export data for
     * @param tenantId - The tenant context
     * @returns Complete export data structure
     * @throws ForbiddenError if authorization fails
     * @throws StatementTimeoutError if the query exceeds the long query timeout
     * @throws CircuitBreakerOpenError if the GDPR service circuit breaker is open
     */
    exportUserData(authContext: GdprAuthorizationContext, userId: ID, tenantId: ID): Promise<GdprExportData>;
    /**
     * Create an async export request (queues the export job)
     *
     * REQUIRES: GdprAuthorizationContext must be provided and valid.
     *
     * @param authContext - Authorization context from JWT (REQUIRED)
     * @param userId - The user/entity ID to export data for
     * @param tenantId - The tenant context
     * @returns Export request record
     * @throws ForbiddenError if authorization fails
     */
    createExportRequest(authContext: GdprAuthorizationContext, userId: ID, tenantId: ID): Promise<GdprExportRequest>;
    /**
     * Get export request status
     *
     * REQUIRES: GdprAuthorizationContext must be provided and valid.
     *
     * @param authContext - Authorization context from JWT (REQUIRED)
     * @param requestId - The export request ID
     * @param tenantId - The tenant context for validation
     * @returns Export request or null if not found/expired
     * @throws ForbiddenError if authorization fails
     */
    getExportRequest(authContext: GdprAuthorizationContext, requestId: ID, tenantId: ID): Promise<GdprExportRequest | null>;
    /**
     * Update export request status
     *
     * @param requestId - The export request ID
     * @param updates - Fields to update
     */
    updateExportRequest(requestId: ID, updates: Partial<GdprExportRequest>): Promise<GdprExportRequest | null>;
    /**
     * Store completed export data
     *
     * @param requestId - The export request ID
     * @param data - The export data
     */
    storeExportData(requestId: ID, data: GdprExportData): Promise<string>;
    /**
     * Get stored export data for download
     *
     * REQUIRES: GdprAuthorizationContext must be provided and valid.
     *
     * @param authContext - Authorization context from JWT (REQUIRED)
     * @param requestId - The export request ID
     * @param tenantId - The tenant context for validation
     * @returns Export data or null if not found/expired
     * @throws ForbiddenError if authorization fails
     */
    getExportData(authContext: GdprAuthorizationContext, requestId: ID, tenantId: ID): Promise<GdprExportData | null>;
    /**
     * Soft delete all user data (Article 17 - Right to Erasure)
     * Protected by circuit breaker to prevent cascading failures.
     *
     * REQUIRES: GdprAuthorizationContext must be provided and valid.
     * NOTE: For non-self erasure, authContext.hasExplicitConsent must be true.
     *
     * @param authContext - Authorization context from JWT (REQUIRED)
     * @param userId - The user/entity ID to erase data for
     * @param tenantId - The tenant context
     * @returns Erasure result with counts
     * @throws ForbiddenError if authorization fails
     * @throws CircuitBreakerOpenError if the GDPR service circuit breaker is open
     */
    eraseUserData(authContext: GdprAuthorizationContext, userId: ID, tenantId: ID): Promise<GdprErasureResult>;
}
/**
 * Get or create the GDPR export queue
 */
export declare function getGdprExportQueue(): Queue;
/**
 * Enqueue a GDPR export job
 *
 * Authorization is already validated when createExportRequest is called.
 * The authContext is stored with the job so the worker can record proper audit trails.
 *
 * @param requestId - The export request ID
 * @param userId - The user to export data for
 * @param tenantId - The tenant context
 * @param authContext - The validated authorization context
 */
export declare function enqueueGdprExport(requestId: ID, userId: ID, tenantId: ID, authContext: GdprAuthorizationContext): Promise<void>;
/**
 * Register GDPR export worker
 */
export declare function registerGdprWorker(): void;
/**
 * Shutdown GDPR export worker
 */
export declare function shutdownGdprWorker(): Promise<void>;
/**
 * Create a new GDPR service instance with dependency injection.
 *
 * This is the preferred way to create services in production code
 * as it makes dependencies explicit and testable.
 *
 * @param deps - Optional dependencies. If not provided, uses global singletons.
 * @returns Configured GdprService instance
 *
 * @example
 * // Default usage (backward compatible)
 * const service = createGdprService();
 *
 * @example
 * // With custom dependencies
 * const service = createGdprService({
 *   database: customDb,
 *   redis: customRedis,
 *   config: customConfig,
 * });
 */
export declare function createGdprService(deps?: GdprServiceDependencies): GdprService;
//# sourceMappingURL=gdpr.d.ts.map