/**
 * Validation utilities for HSN and SAC codes
 */

export interface ValidationResult {
    isValid: boolean;
    message: string;
}

/**
 * Validates HSN or SAC code based on GST rules
 * @param code The HSN/SAC code string
 * @param isService Boolean indicating if it's a Service (SAC) or Goods (HSN)
 * @returns ValidationResult object
 */
export const validateHSNSAC = (code: string, isService: boolean): ValidationResult => {
    if (!code) return { isValid: true, message: '' };

    const cleanCode = code.trim();

    // Basic check for digits only
    if (!/^\d+$/.test(cleanCode)) {
        return { isValid: false, message: 'Code must contain only digits' };
    }

    if (isService) {
        // SAC (Services Accounting Code)
        // Must start with 99 and typically has 6 digits
        if (!cleanCode.startsWith('99')) {
            return { isValid: false, message: 'SAC (Service) code must start with 99' };
        }
        if (cleanCode.length !== 6) {
            return { isValid: false, message: 'SAC code must be exactly 6 digits' };
        }
    } else {
        // HSN (Harmonized System of Nomenclature) for Goods
        // Usually 4, 6, or 8 digits in India
        const validHSNLengths = [4, 6, 8];
        if (!validHSNLengths.includes(cleanCode.length)) {
            return { isValid: false, message: 'HSN code must be 4, 6, or 8 digits' };
        }

        // HSN codes for goods should generally not start with 99 (that's reserved for SAC)
        if (cleanCode.startsWith('99')) {
            return { isValid: false, message: 'HSN code should not start with 99 (use SAC type for services)' };
        }
    }

    return { isValid: true, message: '' };
};
