// Utility functions for building SQL queries safely

/**
 * Builds WHERE clause from filter object
 * Returns [sqlFragment, params] for safe parameterized queries
 */
export function buildWhere(
    filters: Record<string, any>,
    startIndex: number = 1
): [string, any[]] {
    const conditions: string[] = [];
    const params: any[] = [];
    let paramIndex = startIndex;

    Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
            conditions.push(`${key} = $${paramIndex++}`);
            params.push(value);
        }
    });

    const sql = conditions.length > 0 ? ` AND ${conditions.join(' AND ')}` : '';
    return [sql, params];
}

/**
 * Builds LIKE clause for search
 */
export function buildSearch(
    column: string,
    searchTerm: string,
    paramIndex: number
): [string, string] {
    return [` AND ${column} ILIKE $${paramIndex}`, `%${searchTerm}%`];
}

/**
 * Builds pagination clause
 */
export function buildPagination(
    limit: number = 50,
    offset: number = 0,
    paramIndex: number
): [string, number, number] {
    return [
        ` LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`,
        Math.min(limit, 1000), // Cap at 1000
        Math.max(offset, 0)
    ];
}

/**
 * Sanitizes table/column names (only allow alphanumeric + underscore)
 */
export function sanitizeIdentifier(identifier: string): string {
    if (!/^[a-zA-Z0-9_]+$/.test(identifier)) {
        throw new Error(`Invalid identifier: ${identifier}`);
    }
    return identifier;
}

/**
 * Builds dynamic UPDATE SET clause
 */
export function buildUpdateSet(
    data: Record<string, any>,
    startIndex: number = 1
): [string, any[]] {
    const fields: string[] = [];
    const values: any[] = [];
    let paramIndex = startIndex;

    Object.entries(data).forEach(([key, value]) => {
        if (value !== undefined && key !== 'id' && key !== 'created_at') {
            fields.push(`${sanitizeIdentifier(key)} = $${paramIndex++}`);
            values.push(value);
        }
    });

    if (fields.length === 0) {
        throw new Error('No fields to update');
    }

    return [fields.join(', '), values];
}

/**
 * Executes a query and returns single result or null
 */
export function getSingleResult<T>(rows: T[]): T | null {
    return rows[0] || null;
}

/**
 * Validates UUID format
 */
export function isValidUUID(uuid: string): boolean {
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    return uuidRegex.test(uuid);
}
