const express = require('express');
const multer = require('multer');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const pdfParse = require('pdf-parse');

const app = express();
const upload = multer({ dest: 'uploads/temp/' });

app.use(cors());
app.use(express.json());

// Mock auth endpoint
app.post('/api/auth/login', (req, res) => {
  const { username, password } = req.body;
  if (username === 'admin' && password === 'admin') {
    res.json({
      success: true,
      data: {
        token: 'mock-token',
        user: {
          id: '1',
          username: 'admin',
          role: 'admin'
        }
      }
    });
  } else {
    res.status(401).json({ success: false, error: { message: 'Invalid credentials' } });
  }
});

// Mock organization hierarchy
app.get('/api/organization/hierarchy', (req, res) => {
  res.json({
    success: true,
    data: [
      {
        id: '1',
        code: 'DIR',
        name: 'Direktor LKA NRW',
        type: 'direktion',
        level: 0,
        parentId: null,
        children: []
      }
    ]
  });
});

// PDF Import endpoint
app.post('/api/organization/import-pdf', upload.single('pdf'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        error: { message: 'No PDF file uploaded' }
      });
    }

    const pdfBuffer = fs.readFileSync(req.file.path);
    
    // Parse PDF
    try {
      const pdfData = await pdfParse(pdfBuffer);
      console.log('PDF parsed:', pdfData.numpages, 'pages');
      console.log('Text preview:', pdfData.text.substring(0, 500));
      
      // Simplified parsing
      const lines = pdfData.text.split('\n').filter(line => line.trim());
      const units = [];
      
      lines.forEach(line => {
        if (line.includes('Direktor')) {
          units.push({ code: 'DIR', name: 'Direktor LKA NRW', type: 'direktion' });
        } else if (line.match(/Abteilung\s+\d+/)) {
          const match = line.match(/Abteilung\s+(\d+)/);
          units.push({ 
            code: `Abt ${match[1]}`, 
            name: line.trim(), 
            type: 'abteilung' 
          });
        } else if (line.match(/Dezernat\s+\d+/)) {
          const match = line.match(/Dezernat\s+(\d+)/);
          units.push({ 
            code: `Dez ${match[1]}`, 
            name: line.trim(), 
            type: 'dezernat' 
          });
        }
      });
      
      // Clean up temp file
      fs.unlinkSync(req.file.path);
      
      res.json({
        success: true,
        data: {
          message: `Successfully imported ${units.length} organizational units from PDF`,
          unitsImported: units.length,
          units: units
        }
      });
      
    } catch (parseError) {
      console.error('PDF parse error:', parseError);
      fs.unlinkSync(req.file.path);
      
      // Fallback response
      res.json({
        success: true,
        data: {
          message: 'Imported sample organizational units (PDF parsing failed)',
          unitsImported: 5,
          units: [
            { code: 'DIR', name: 'Direktor LKA NRW', type: 'direktion' },
            { code: 'Abt 1', name: 'Abteilung 1 - OK', type: 'abteilung' },
            { code: 'Abt 2', name: 'Abteilung 2 - Staatsschutz', type: 'abteilung' },
            { code: 'Dez 11', name: 'Dezernat 11', type: 'dezernat' },
            { code: 'SG 11.1', name: 'Sachgebiet 11.1', type: 'sachgebiet' }
          ]
        }
      });
    }
    
  } catch (error) {
    console.error('Import error:', error);
    res.status(500).json({
      success: false,
      error: { message: 'Failed to import PDF: ' + error.message }
    });
  }
});

const PORT = 3004;
app.listen(PORT, () => {
  console.log(`Mock backend server running on http://localhost:${PORT}`);
  console.log('Login with admin/admin');
  console.log('PDF import endpoint ready at POST /api/organization/import-pdf');
});