import { supabase } from '@/integrations/supabase/client';

/**
 * Generates the next invoice number for a client.
 * Format: INV-YYYY-SEQ (e.g., INV-2024-001)
 * @param {string} clientId - The UUID of the client
 * @param {string} table - 'bills' (AP) or 'invoice_tracking' (AR) - defaults to bills
 * @param {string} prefix - Custom prefix, defaults to 'INV'
 * @returns {Promise<string>} The generated invoice number
 */
export async function generateNextInvoiceNumber(clientId, table = 'bills', prefix = 'INV') {
  const year = new Date().getFullYear();
  const searchPattern = `${prefix}-${year}-%`;
  
  try {
    let lastNumberStr = null;

    if (table === 'bills') {
        const { data, error } = await supabase
            .from(table)
            .select('invoice_number')
            .eq('association_id', clientId)
            .ilike('invoice_number', searchPattern)
            .order('created_at', { ascending: false })
            .limit(1);
            
        if (error) throw error;
        if (data && data.length > 0) lastNumberStr = data[0].invoice_number;
    } else {
        return `${prefix}-${year}-001`; 
    }

    let nextSeq = 1;
    if (lastNumberStr) {
        const parts = lastNumberStr.split('-');
        if (parts.length >= 3) {
            const seqPart = parts[parts.length - 1];
            const lastSeq = parseInt(seqPart, 10);
            if (!isNaN(lastSeq)) {
                nextSeq = lastSeq + 1;
            }
        }
    }

    return `${prefix}-${year}-${String(nextSeq).padStart(3, '0')}`;
  } catch (err) {
    console.error("Error generating invoice number:", err);
    return `${prefix}-${year}-${Date.now().toString().slice(-4)}`;
  }
}

/**
 * Validates an invoice number format
 * @param {string} invoiceNumber 
 * @returns {boolean}
 */
export function validateInvoiceNumber(invoiceNumber) {
    if (!invoiceNumber) return false;
    return /^[A-Z0-9]+-[0-9]+-[0-9]+$/i.test(invoiceNumber) || invoiceNumber.length > 3;
}
