/**
 * Serial Number Utilities
 *
 * Functions for generating auto-incremented serial numbers for Stock Movement Sheets.
 * Format: SMS-00001, SMS-00002, etc.
 */

import { getStockMovementSheets, type StockMovementSheet } from "@/lib/api";

/**
 * Fetches the last Stock Movement Sheet and generates the next serial number.
 * 
 * @returns Promise<string> - The next serial number in format "SMS-00001"
 * 
 * @example
 * const nextSerial = await generateNextSerialNumber();
 * // Returns "SMS-00001" if no sheets exist
 * // Returns "SMS-00124" if last sheet was "SMS-00123"
 */
export async function generateNextSerialNumber(): Promise<string> {
  try {
    // Fetch all sheets and get the most recent one
    const sheets = await getStockMovementSheets();
    
    if (sheets.length === 0) {
      // No previous sheets exist, start at 1
      return "SMS-00001";
    }

    // Sort by createdAt descending to get the most recent sheet
    const sortedSheets = [...sheets].sort((a, b) => 
      new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    );
    
    const lastSheet = sortedSheets[0];
    
    // Extract and increment the serial number
    return incrementSerialNumber(lastSheet.documentNumber);
  } catch (error) {
    console.error("Error generating serial number:", error);
    // Fallback to SMS-00001 on error
    return "SMS-00001";
  }
}

/**
 * Parses a document number and increments it.
 * 
 * @param documentNumber - The current document number (e.g., "SMS-00123")
 * @returns string - The next serial number (e.g., "SMS-00124")
 * 
 * Handles various formats:
 * - "SMS-00123" → "SMS-00124"
 * - "SMS-123" → "SMS-00124"
 * - "00123" → "SMS-00124"
 * - null/undefined → "SMS-00001"
 * - Malformed → "SMS-00001"
 */
export function incrementSerialNumber(documentNumber: string | null | undefined): string {
  if (!documentNumber) {
    return "SMS-00001";
  }

  try {
    // Extract numeric portion from various formats
    // Matches: "SMS-00123", "SMS-123", "00123", "123", etc.
    const match = documentNumber.match(/(\d+)/);
    
    if (!match) {
      // No numeric portion found, start at 1
      return "SMS-00001";
    }

    const currentNumber = parseInt(match[1], 10);
    
    if (isNaN(currentNumber)) {
      // Invalid number, start at 1
      return "SMS-00001";
    }

    // Increment and format with zero-padding (5 digits)
    const nextNumber = currentNumber + 1;
    return formatSerialNumber(nextNumber);
  } catch (error) {
    console.error("Error parsing serial number:", error);
    return "SMS-00001";
  }
}

/**
 * Formats a number as a serial number with zero-padding.
 * 
 * @param number - The numeric portion of the serial number
 * @returns string - Formatted serial number (e.g., "SMS-00123")
 * 
 * @example
 * formatSerialNumber(1) // "SMS-00001"
 * formatSerialNumber(123) // "SMS-00123"
 * formatSerialNumber(12345) // "SMS-12345"
 */
export function formatSerialNumber(number: number): string {
  // Zero-pad to 5 digits
  const paddedNumber = String(number).padStart(5, "0");
  return `SMS-${paddedNumber}`;
}

/**
 * Validates a serial number format.
 * 
 * @param serialNumber - The serial number to validate
 * @returns boolean - True if valid format, false otherwise
 * 
 * @example
 * isValidSerialNumber("SMS-00123") // true
 * isValidSerialNumber("SMS-123") // false (not zero-padded)
 * isValidSerialNumber("ABC-00123") // false (wrong prefix)
 */
export function isValidSerialNumber(serialNumber: string): boolean {
  // Valid format: SMS-00001 to SMS-99999
  const pattern = /^SMS-\d{5}$/;
  return pattern.test(serialNumber);
}
