import { Router } from 'express'
import multer from 'multer'
import { v4 as uuidv4 } from 'uuid'
import fs from 'fs'
import path from 'path'
const pdfParse = require('pdf-parse')
import { db } from '../config/secureDatabase'
import { authenticate, authorize, AuthRequest } from '../middleware/auth'
import { logger } from '../utils/logger'

const router = Router()

// Configure multer for PDF uploads
const upload = multer({
  dest: 'uploads/temp/',
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB limit
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype === 'application/pdf') {
      cb(null, true)
    } else {
      cb(new Error('Only PDF files are allowed'))
    }
  }
})

// Helper to parse organizational structure from PDF text
function parseOrganizationFromText(text: string) {
  const units: any[] = []
  const byCode = new Map<string, any>()
  const rawLines = text.split('\n').map(line => line.trim()).filter(line => line && line.length > 2)

  const patterns = {
    direktor: /(Direktor|Director)\s*(LKA)?/i,
    abteilung: /^Abteilung\s+(\d+|Zentralabteilung)/i,
    dezernat: /^(?:Dezernat|Dez)\s+([\d]+)/i,
    sachgebiet: /^SG\s+([\d\.]+)/i,
    teildezernat: /^TD\s+([\d\.]+)/i,
    stabsstelle: /(Leitungsstab|LStab|Führungsgruppe)/i,
    sondereinheit: /(Personalrat|Schwerbehindertenvertretung|Datenschutzbeauftrag|Gleichstellungsbeauftrag|Innenrevision|IUK-Lage)/i
  }

  const colors: Record<string, string> = {
    '1': '#dc2626', '2': '#ea580c', '3': '#0891b2', '4': '#7c3aed', '5': '#0d9488', '6': '#be185d', 'ZA': '#6b7280'
  }

  // Join wrapped description lines to their header lines to avoid losing info across line breaks
  // Recognize headers that start a new unit and merge subsequent non-header lines into the previous one
  const headerRegex = new RegExp(
    '^(?:' +
      'Abteilung\\s+(?:\\d+|Zentralabteilung)' +
      '|Zentralabteilung\\b' +
      '|ZA\\b' +
      '|(?:Dezernat|Dez)\\s+' +
      '|SG\\s+' +
      '|TD\\s+' +
      '|Direktor' +
      '|Director' +
      '|Leitungsstab' +
      '|LStab' +
      '|Führungsgruppe' +
      '|Personalrat' +
      '|Schwerbehindertenvertretung' +
      '|Datenschutzbeauftrag' +
      '|Gleichstellungsbeauftrag' +
      '|Innenrevision' +
      '|IUK-Lage' +
    ')',
    'i'
  )
  const lines: string[] = []
  for (const original of rawLines) {
    const line = original.replace(/[–—]/g, '-')
    if (lines.length === 0 || headerRegex.test(line)) {
      lines.push(line)
    } else {
      // continuation line: append to previous with spacing; handle hyphenation
      const lastIdx = lines.length - 1
      const prev = lines[lastIdx]
      if (/[-–—]$/.test(prev)) {
        lines[lastIdx] = prev.replace(/[-–—]$/, '') + line
      } else if (/[,:;]$/.test(prev)) {
        lines[lastIdx] = prev + ' ' + line
      } else {
        lines[lastIdx] = prev + ' ' + line
      }
    }
  }

  const ensure = (u: any) => {
    const existing = byCode.get(u.code)
    if (existing) {
      // Update minimal fields if missing
      existing.name = existing.name || u.name
      existing.type = existing.type || u.type
      existing.level = existing.level ?? u.level
      if (!existing.parentId && u.parentId) existing.parentId = u.parentId
      if (!existing.color && u.color) existing.color = u.color
      return existing
    }
    byCode.set(u.code, u)
    units.push(u)
    return u
  }

  const inferAbteilungCode = (dezNum: string) => {
    const digits = (dezNum || '').replace(/\D/g, '')
    const first = digits.charAt(0)
    if (['1','2','3','4','5','6'].includes(first)) return `Abt ${first}`
    if (dezNum.toUpperCase().includes('ZA') || first === '0') return 'Abt ZA'
    return null
  }

  let currentAbteilung: any = null
  let currentDezernat: any = null

  // Always ensure root
  ensure({ code: 'DIR', name: 'Direktor LKA NRW', type: 'direktion', level: 0, parentId: null, color: '#1e3a8a' })

  for (const raw of lines) {
    const line = raw.replace(/[–—]/g, '-')

    if (patterns.direktor.test(line)) {
      ensure({ code: 'DIR', name: 'Direktor LKA NRW', type: 'direktion', level: 0, parentId: null, color: '#1e3a8a' })
      continue
    }

    // Abteilung (inkl. Zentralabteilung erkennen)
    const abtMatch = line.match(/Abteilung\s+(\d+|Zentralabteilung)/i)
    if (abtMatch) {
      const abtNum = abtMatch[1] === 'Zentralabteilung' ? 'ZA' : abtMatch[1]
      const abtName = line.replace(/^Abteilung\s+(?:\d+|Zentralabteilung)\s*-?\s*/i, '').trim() || `Abteilung ${abtNum}`
      currentAbteilung = ensure({
        code: `Abt ${abtNum}`,
        name: abtName,
        type: 'abteilung',
        level: 1,
        parentId: 'DIR',
        color: colors[abtNum] || '#6b7280',
        hasFuehrungsstelle: abtNum !== 'ZA'
      })
      currentDezernat = null
      continue
    }

    // Zentralabteilung alleinstehend (ohne Präfix "Abteilung")
    if (/^Zentralabteilung\b/i.test(line) || /^ZA\b/i.test(line)) {
      currentAbteilung = ensure({
        code: 'Abt ZA',
        name: 'Zentralabteilung',
        type: 'abteilung',
        level: 1,
        parentId: 'DIR',
        color: colors['ZA'] || '#6b7280',
        hasFuehrungsstelle: false
      })
      currentDezernat = null
      // nicht continue; nachfolgende Muster können weitere Details liefern
    }

    // Dezernat ZA N (z. B. "Dez ZA 1" bis "Dez ZA 5")
    const dezZaMatch = line.match(/^(?:Dezernat|Dez)\s+ZA\s*(\d{1,2})/i)
    if (dezZaMatch) {
      const zaNum = dezZaMatch[1].trim()
      const dezName = line.replace(/^(?:Dezernat|Dez)\s+ZA\s*\d{1,2}\s*-?\s*/i, '').trim() || `Dezernat ZA ${zaNum}`
      // Ensure Abt ZA exists
      ensure({ code: 'Abt ZA', name: 'Zentralabteilung', type: 'abteilung', level: 1, parentId: 'DIR', color: colors['ZA'] || '#6b7280', hasFuehrungsstelle: false })
      currentDezernat = ensure({ code: `Dez ZA ${zaNum}`, name: dezName, type: 'dezernat', level: 2, parentId: 'Abt ZA' })
      continue
    }

    const dezMatch = line.match(/^(?:Dezernat|Dez)\s+([\d]+)/i)
    if (dezMatch) {
      const dezNum = dezMatch[1].trim()
      const dezName = line.replace(/^(?:Dezernat|Dez)\s+[\d]+\s*-?\s*/i, '').trim() || `Dezernat ${dezNum}`
      // Strict mapping: first digit of dezNum determines Abteilung
      const inferredAbt = inferAbteilungCode(dezNum)
      let parentCode: string | null = null
      if (inferredAbt) {
        const abtNum = inferredAbt.split(' ')[1]
        ensure({ code: inferredAbt, name: inferredAbt.replace('Abt', 'Abteilung'), type: 'abteilung', level: 1, parentId: 'DIR', color: colors[abtNum] || '#6b7280', hasFuehrungsstelle: abtNum !== 'ZA' })
        parentCode = inferredAbt
      }
      currentDezernat = ensure({ code: `Dez ${dezNum}`, name: dezName, type: 'dezernat', level: 2, parentId: parentCode })
      continue
    }

    // Sachgebiet ZA X.Y (z. B. "SG ZA 3.1 - ...")
    const sgZaMatch = line.match(/^SG\s+ZA\s+(\d+)\.(\d+)/i)
    if (sgZaMatch) {
      const main = sgZaMatch[1].trim()
      const sub = sgZaMatch[2].trim()
      const sgName = line.replace(/^SG\s+ZA\s+\d+\.\d+\s*-?\s*/i, '').trim() || `Sachgebiet ZA ${main}.${sub}`
      // Ensure Abt ZA and Dez ZA X
      ensure({ code: 'Abt ZA', name: 'Zentralabteilung', type: 'abteilung', level: 1, parentId: 'DIR', color: colors['ZA'] || '#6b7280', hasFuehrungsstelle: false })
      ensure({ code: `Dez ZA ${main}`, name: `Dezernat ZA ${main}`, type: 'dezernat', level: 2, parentId: 'Abt ZA' })
      ensure({ code: `SG ZA ${main}.${sub}`, name: sgName, type: 'sachgebiet', level: 3, parentId: `Dez ZA ${main}` })
      continue
    }

    // Sachgebiet Leitungsstab (z. B. "SG LStab 1 - ...")
    const sgLStabMatch = line.match(/^SG\s+LStab\s+(\d+)/i)
    if (sgLStabMatch) {
      const num = sgLStabMatch[1].trim()
      const sgName = line.replace(/^SG\s+LStab\s+\d+\s*-?\s*/i, '').trim() || `Sachgebiet LStab ${num}`
      // Ensure Leitungsstab exists under DIR
      ensure({ code: 'LStab', name: 'Leitungsstab', type: 'stabsstelle', level: 1, parentId: 'DIR', color: '#6b7280' })
      ensure({ code: `SG LStab ${num}`, name: sgName, type: 'sachgebiet', level: 2, parentId: 'LStab' })
      continue
    }

    const sgMatch = line.match(/^SG\s+([\d\.]+)/i)
    if (sgMatch) {
      const sgNum = sgMatch[1].trim()
      const sgName = line.replace(/^SG\s+[\d\.]+\s*-?\s*/i, '').trim() || `Sachgebiet ${sgNum}`
      // Strict mapping: SG NN.X -> Dez NN under Abt N
      const prefix = sgNum.split('.')[0]
      let dezCode: string | null = null
      if (prefix) {
        dezCode = `Dez ${prefix}`
        const inferredAbt = inferAbteilungCode(prefix)
        if (inferredAbt) {
          const abtNum = inferredAbt.split(' ')[1]
          ensure({ code: inferredAbt, name: inferredAbt.replace('Abt', 'Abteilung'), type: 'abteilung', level: 1, parentId: 'DIR', color: colors[abtNum] || '#6b7280', hasFuehrungsstelle: abtNum !== 'ZA' })
        }
        ensure({ code: dezCode, name: `Dezernat ${prefix}`, type: 'dezernat', level: 2, parentId: inferredAbt || null })
      }
      ensure({ code: `SG ${sgNum}`, name: sgName, type: 'sachgebiet', level: 3, parentId: dezCode })
      continue
    }

    // Teildezernat ZA X.Y (z. B. "TD ZA 2.1 - ...")
    const tdZaMatch = line.match(/^TD\s+ZA\s+(\d+)\.(\d+)/i)
    if (tdZaMatch) {
      const main = tdZaMatch[1].trim()
      const sub = tdZaMatch[2].trim()
      const tdName = line.replace(/^TD\s+ZA\s+\d+\.\d+\s*-?\s*/i, '').trim() || `Teildezernat ZA ${main}.${sub}`
      // Ensure Abt ZA and Dez ZA X
      ensure({ code: 'Abt ZA', name: 'Zentralabteilung', type: 'abteilung', level: 1, parentId: 'DIR', color: colors['ZA'] || '#6b7280', hasFuehrungsstelle: false })
      ensure({ code: `Dez ZA ${main}`, name: `Dezernat ZA ${main}`, type: 'dezernat', level: 2, parentId: 'Abt ZA' })
      ensure({ code: `TD ZA ${main}.${sub}`, name: tdName, type: 'teildezernat', level: 3, parentId: `Dez ZA ${main}` })
      continue
    }

    const tdMatch = line.match(/^TD\s+([\d\.]+)/i)
    if (tdMatch) {
      const tdNum = tdMatch[1].trim()
      const tdName = line.replace(/^TD\s+[\d\.]+\s*-?\s*/i, '').trim() || `Teildezernat ${tdNum}`
      // Strict mapping: TD NN.X -> Dez NN under Abt N
      const prefix = tdNum.split('.')[0]
      let dezCode: string | null = null
      if (prefix) {
        dezCode = `Dez ${prefix}`
        const inferredAbt = inferAbteilungCode(prefix)
        if (inferredAbt) {
          const abtNum = inferredAbt.split(' ')[1]
          ensure({ code: inferredAbt, name: inferredAbt.replace('Abt', 'Abteilung'), type: 'abteilung', level: 1, parentId: 'DIR', color: colors[abtNum] || '#6b7280', hasFuehrungsstelle: abtNum !== 'ZA' })
        }
        ensure({ code: dezCode, name: `Dezernat ${prefix}`, type: 'dezernat', level: 2, parentId: inferredAbt || null })
      }
      ensure({ code: `TD ${tdNum}`, name: tdName, type: 'teildezernat', level: 3, parentId: dezCode })
      continue
    }

    if (patterns.stabsstelle.test(line)) {
      ensure({ code: 'LStab', name: 'Leitungsstab', type: 'stabsstelle', level: 1, parentId: 'DIR', color: '#6b7280' })
      continue
    }

    if (patterns.sondereinheit.test(line)) {
      let code = 'SE'
      let name = line
      if (/Personalrat/i.test(line)) { code = 'PR'; name = 'Personalrat' }
      else if (/Schwerbehindertenvertretung/i.test(line)) { code = 'SBV'; name = 'Schwerbehindertenvertretung' }
      else if (/Datenschutzbeauftrag/i.test(line)) { code = 'DSB'; name = 'Datenschutzbeauftragter' }
      else if (/Gleichstellungsbeauftrag/i.test(line)) { code = 'GSB'; name = 'Gleichstellungsbeauftragte' }
      else if (/Innenrevision/i.test(line)) { code = 'IR'; name = 'Innenrevision' }
      ensure({ code, name, type: 'sondereinheit', level: 1, parentId: null, color: '#059669' })
      continue
    }
  }

  // Post-processing: infer missing parents
  const has = (code: string) => byCode.has(code)
  const get = (code: string) => byCode.get(code)
  for (const u of units) {
    if (u.type === 'dezernat' && !u.parentId) {
      const inferred = inferAbteilungCode(String(u.code).replace(/^Dez\s+/i,''))
      if (inferred) {
        if (!has(inferred)) {
          const abtNum = inferred.split(' ')[1]
          ensure({ code: inferred, name: inferred.replace('Abt', 'Abteilung'), type: 'abteilung', level: 1, parentId: 'DIR', color: colors[abtNum] || '#6b7280', hasFuehrungsstelle: abtNum !== 'ZA' })
        }
        u.parentId = inferred
      }
    }
    if ((u.type === 'sachgebiet' || u.type === 'teildezernat') && !u.parentId) {
      const num = String(u.code).replace(/^(SG|TD)\s+/i,'')
      const prefix = num.split('.')[0]
      if (prefix) {
        const dezCode = `Dez ${prefix}`
        if (!has(dezCode)) {
          ensure({ code: dezCode, name: `Dezernat ${prefix}`, type: 'dezernat', level: 2, parentId: inferAbteilungCode(prefix) })
        }
        u.parentId = dezCode
      }
    }
  }

  return units
}

// Import organization from PDF
router.post('/import-pdf', 
  authenticate, 
  authorize('admin'),
  upload.single('pdf'),
  async (req: AuthRequest, res: any, next: any) => {
    let tempFilePath: string | null = null
    
    try {
      if (!req.file) {
        return res.status(400).json({ 
          success: false, 
          error: { message: 'No PDF file uploaded' } 
        })
      }
      
      tempFilePath = req.file.path
      
      // Read PDF file
      const pdfBuffer = fs.readFileSync(tempFilePath)
      
      // Parse PDF using pdf-parse
      let extractedText = ''
      try {
        const pdfData = await pdfParse(pdfBuffer)
        extractedText = pdfData.text
        
        logger.info(`PDF parsed successfully: ${pdfData.numpages} pages, ${extractedText.length} characters`)
      } catch (parseError) {
        logger.error('PDF parsing error:', parseError)
        // Fallback to simulated data if parsing fails
        extractedText = `
          Direktor LKA NRW
          Leitungsstab
          Personalrat
          Schwerbehindertenvertretung
          Abteilung 1 - Organisierte Kriminalität
          Dezernat 11 - Ermittlungen OK
          SG 11.1 - Grundsatzfragen
          Dezernat 12 - Wirtschaftskriminalität
          Abteilung 2 - Terrorismusbekämpfung
          Dezernat 21 - Ermittlungen
          Abteilung 3 - Strategische Kriminalitätsbekämpfung
          Abteilung 4 - Cybercrime
          Abteilung 5 - Kriminalwissenschaftliches Institut
          Abteilung 6 - Fachaufsicht
          Zentralabteilung
        `
      }
      
      // Parse the organizational structure
      let parsedUnits = parseOrganizationFromText(extractedText)

      // Apply saved import rules (overrides)
      try {
        const rules = db.prepare('SELECT target_code, parent_code, type_override, name_override FROM organization_import_rules').all() as any[]
        if (rules && rules.length) {
          const byCode: Record<string, any> = {}
          parsedUnits.forEach(u => { byCode[u.code] = u })
          rules.forEach(r => {
            const u = byCode[r.target_code]
            if (u) {
              if (r.parent_code) u.parentId = r.parent_code
              if (r.type_override) u.type = r.type_override
              if (r.name_override) u.name = r.name_override
            }
          })
        }
      } catch {}
      
      if (parsedUnits.length === 0) {
        return res.status(400).json({
          success: false,
          error: { message: 'No organizational units could be extracted from the PDF' }
        })
      }
      
      // PREVIEW MODE: if requested, compute diff and return without writing
      const previewOnly = String((req.body as any).previewOnly ?? (req.query as any).previewOnly) === 'true'
      const overridesRaw = (req.body as any).overrides ?? (req.query as any).overrides
      let overrides: Array<{ code: string; parentCode?: string; type?: string; name?: string }> = []
      try {
        if (overridesRaw) overrides = typeof overridesRaw === 'string' ? JSON.parse(overridesRaw) : overridesRaw
      } catch {}

      if (overrides.length) {
        const byCode: Record<string, any> = {}
        parsedUnits.forEach(u => { byCode[u.code] = u })
        overrides.forEach(o => {
          const u = byCode[o.code]
          if (u) {
            if (o.parentCode) u.parentId = o.parentCode
            if (o.type) u.type = o.type
            if (o.name) u.name = o.name
          }
        })
      }

      const now = new Date().toISOString()

      const existingMap = new Map<string, any>()
      const existingRows = db.prepare(`SELECT id, code, name, type, level, parent_id as parentId FROM organizational_units`).all() as any[]
      existingRows.forEach(r => existingMap.set(r.code, r))

      // Diff classification
      const orphans: any[] = []
      const toCreate: any[] = []
      const toUpdate: any[] = []
      parsedUnits.forEach(u => {
        const parentCode = u.parentId || null
        const exists = existingMap.get(u.code)
        if (!parentCode) {
          orphans.push(u)
        }
        if (!exists) {
          toCreate.push(u)
        } else {
          const diff = (exists.name !== u.name) || (exists.type !== u.type) || (exists.level !== u.level)
          // Parent diff: compare codes by looking up parent id -> code
          let existingParentCode: string | null = null
          if (exists.parentId) {
            const parentRow = db.prepare('SELECT code FROM organizational_units WHERE id = ?').get(exists.parentId) as any
            existingParentCode = parentRow?.code || null
          }
          const parentDiff = existingParentCode !== parentCode
          if (diff || parentDiff) {
            toUpdate.push({ existing: exists, incoming: u })
          }
        }
      })

      if (previewOnly) {
        return res.json({ success: true, data: { 
          message: 'Preview generated',
          counts: { create: toCreate.length, update: toUpdate.length, orphans: orphans.length },
          diff: { create: toCreate, update: toUpdate, orphans }
        }})
      }

      // Clear existing organization (optional)
      if (((req.body as any).clearExisting ?? (req.query as any).clearExisting) === 'true') {
        db.prepare('DELETE FROM organizational_units').run()
      }

      // Prepare insert/update with stable parent references and FK-safe order
      const unitIdMap: Record<string, string> = {}
      for (const unit of parsedUnits) {
        const existing = db.prepare('SELECT id FROM organizational_units WHERE code = ?').get(unit.code) as any
        unitIdMap[unit.code] = existing?.id || uuidv4()
      }
      const sorted = [...parsedUnits].sort((a, b) => (a.level ?? 0) - (b.level ?? 0))
      const tx = db.transaction(() => {
        sorted.forEach((unit, index) => {
          const parentId = unit.parentId ? unitIdMap[unit.parentId] : null
          const existing = db.prepare('SELECT id FROM organizational_units WHERE code = ?').get(unit.code) as any
          if (existing) {
            db.prepare(`
              UPDATE organizational_units
              SET name = ?, type = ?, level = ?, parent_id = ?,
                  color = ?, order_index = ?, has_fuehrungsstelle = ?,
                  is_active = 1, updated_at = ?
              WHERE id = ?
            `).run(
              unit.name,
              unit.type,
              unit.level,
              parentId,
              unit.color || null,
              index,
              unit.hasFuehrungsstelle ? 1 : 0,
              now,
              existing.id
            )
          } else {
            db.prepare(`
              INSERT INTO organizational_units (
                id, code, name, type, level, parent_id,
                color, order_index, has_fuehrungsstelle,
                is_active, created_at, updated_at
              ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `).run(
              unitIdMap[unit.code],
              unit.code,
              unit.name,
              unit.type,
              unit.level,
              parentId,
              unit.color || null,
              index,
              unit.hasFuehrungsstelle ? 1 : 0,
              1,
              now,
              now
            )
          }
        })
      })
      tx()

      // Remember rules (optional)
      const rememberRules = String((req.body as any).rememberRules ?? (req.query as any).rememberRules) === 'true'
      if (rememberRules && overrides.length) {
        const upsert = db.prepare(`
          INSERT INTO organization_import_rules (id, target_code, parent_code, type_override, name_override, created_at)
          VALUES (?, ?, ?, ?, ?, ?)
          ON CONFLICT(target_code) DO UPDATE SET parent_code=excluded.parent_code, type_override=excluded.type_override, name_override=excluded.name_override
        `)
        overrides.forEach(o => {
          upsert.run(uuidv4(), o.code, o.parentCode || null, o.type || null, o.name || null, now)
        })
      }
      
      res.json({
        success: true,
        data: {
          message: `Successfully imported ${parsedUnits.length} organizational units`,
          unitsImported: parsedUnits.length,
          units: parsedUnits.map(u => ({
            code: u.code,
            name: u.name,
            type: u.type
          }))
        }
      })
      
    } catch (error) {
      logger.error('Error importing PDF:', error)
      res.status(500).json({
        success: false,
        error: { message: 'Failed to import PDF: ' + (error as Error).message }
      })
    } finally {
      // Clean up temp file
      if (tempFilePath && fs.existsSync(tempFilePath)) {
        fs.unlinkSync(tempFilePath)
      }
    }
  }
)

// Import from structured JSON
router.post('/import-json',
  authenticate,
  authorize('admin'),
  async (req: AuthRequest, res: any, next: any) => {
    try {
      const { units, clearExisting } = req.body
      
      if (!units || !Array.isArray(units)) {
        return res.status(400).json({
          success: false,
          error: { message: 'Invalid units data' }
        })
      }
      
      // Clear existing if requested
      if (clearExisting) {
        db.prepare('DELETE FROM organizational_units').run()
      }
      
      // Import units
      const now = new Date().toISOString()
      units.forEach((unit: any, index: number) => {
        const id = uuidv4()
        db.prepare(`
          INSERT INTO organizational_units (
            id, code, name, type, level, parent_id,
            color, order_index, description,
            has_fuehrungsstelle, is_active, created_at, updated_at
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `).run(
          id,
          unit.code,
          unit.name,
          unit.type,
          unit.level,
          unit.parentId || null,
          unit.color || null,
          index,
          unit.description || null,
          unit.hasFuehrungsstelle ? 1 : 0,
          1,
          now,
          now
        )
      })
      
      res.json({
        success: true,
        data: {
          message: `Successfully imported ${units.length} units`,
          count: units.length
        }
      })
      
    } catch (error) {
      logger.error('Error importing JSON:', error)
      next(error)
    }
  }
)

export default router
