import { db } from '@/lib/db'

interface TrackingNumberConfig {
  format: string
  sequence: number
  sequenceField: string
}

export async function generateTrackingNumber(serviceSlug: string): Promise<string> {
  const settings = await db.systemSettings.findFirst()
  if (!settings) {
    throw new Error('System settings not found')
  }

  let config: TrackingNumberConfig

  switch (serviceSlug) {
    case 'skck':
      config = {
        format: settings.skckNumberFormat,
        sequence: settings.skckSequence,
        sequenceField: 'skckSequence'
      }
      break
    case 'spkt':
      config = {
        format: settings.spktNumberFormat,
        sequence: settings.spktSequence,
        sequenceField: 'spktSequence'
      }
      break
    case 'lalu-lintas':
      config = {
        format: settings.lalinNumberFormat,
        sequence: settings.lalinSequence,
        sequenceField: 'lalinSequence'
      }
      break
    default:
      // Default to SKCK format for unknown services
      config = {
        format: settings.skckNumberFormat,
        sequence: settings.skckSequence,
        sequenceField: 'skckSequence'
      }
  }

  // Generate tracking number
  const trackingNumber = replacePlaceholders(config.format, config.sequence)

  // Update sequence in database
  await db.systemSettings.update({
    where: { id: settings.id },
    data: {
      [config.sequenceField]: config.sequence + 1
    }
  })

  return trackingNumber
}

function replacePlaceholders(format: string, sequence: number): string {
  const now = new Date()
  const year = now.getFullYear().toString()
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')
  
  // Format sequence with leading zeros based on {seq:N} pattern
  const seqMatch = format.match(/\{seq:(\d+)\}/)
  const seqLength = seqMatch ? parseInt(seqMatch[1]) : 4
  const paddedSequence = sequence.toString().padStart(seqLength, '0')

  return format
    .replace(/{YYYY}/g, year)
    .replace(/{MM}/g, month)
    .replace(/{DD}/g, day)
    .replace(/{seq:\d+}/g, paddedSequence)
    .replace(/{seq}/g, paddedSequence)
}

export function getCategoryFromTrackingNumber(trackingNumber: string): string {
  if (trackingNumber.startsWith('SKCK-')) return 'SKCK'
  if (trackingNumber.startsWith('SPKT-')) return 'SPKT'
  if (trackingNumber.startsWith('LL-')) return 'LALU LINTAS'
  return 'LAINNYA'
}

export function getServiceSlugFromTrackingNumber(trackingNumber: string): string {
  if (trackingNumber.startsWith('SKCK-')) return 'skck'
  if (trackingNumber.startsWith('SPKT-')) return 'spkt'
  if (trackingNumber.startsWith('LL-')) return 'lalu-lintas'
  return 'other'
}