
/**
 * Utility for strict validation and normalization of bank transaction types.
 * Enforces the database constraint: CHECK (type IN ('debit', 'credit'))
 */
export function validateAndNormalizeBankTransactionType(rawType, context = 'Unknown') {
    const originalValue = rawType;
    console.warn(`[Validation Debug - PRE] Context: [${context}], Raw type received:`, rawType);
    
    if (rawType === undefined || rawType === null || rawType === '') {
        const errMsg = `BANK TRANSACTION TYPE ERROR: value: [${originalValue}], context: [${context}]. Type cannot be empty. Only 'debit' and 'credit' are allowed.`;
        console.error(errMsg);
        throw new Error(errMsg);
    }
    
    const stringType = String(rawType).toLowerCase().trim();
    let normalizedType = stringType;
    
    // Attempt normalization of common synonyms
    if (['credit', 'deposit', 'income', 'refund'].includes(stringType)) {
        normalizedType = 'credit';
    } else if (['debit', 'withdrawal', 'payment', 'expense', 'charge', 'transfer'].includes(stringType)) {
        normalizedType = 'debit';
    }

    console.warn(`[Validation Debug - POST] Context: [${context}], Normalized type:`, normalizedType);
    
    // Strict final check
    if (normalizedType !== 'debit' && normalizedType !== 'credit') {
        const errMsg = `BANK TRANSACTION TYPE ERROR: value: [${originalValue}], normalized as: [${normalizedType}], context: [${context}]. DB Constraint Violation! Only 'debit' and 'credit' are allowed.`;
        console.error(errMsg);
        throw new Error(errMsg);
    }
    
    return normalizedType;
}
