import { Router } from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import * as contractController from '../controllers/contract.controller.js';
import * as invoiceController from '../controllers/invoice.controller.js';
import * as creditNoteController from '../controllers/creditNote.controller.js';
import { authenticate, requirePermission } from '../middleware/auth.js';
import { validateUploadedFile } from '../middleware/uploadFileTypeValidator.js';

const router = Router();

// Multer für Vertragsdokumente
const docUploadsDir = path.join(process.cwd(), 'uploads', 'contract-documents');
if (!fs.existsSync(docUploadsDir)) {
  fs.mkdirSync(docUploadsDir, { recursive: true });
}
const docUpload = multer({
  storage: multer.diskStorage({
    destination: (_req, _file, cb) => cb(null, docUploadsDir),
    filename: (_req, file, cb) => {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
      cb(null, `doc-${uniqueSuffix}${path.extname(file.originalname)}`);
    },
  }),
  fileFilter: (_req, file, cb) => {
    // Pentest 70.1: aligned mit validateUploadedFile-Whitelist
    // (PDF/JPG/PNG/GIF/WebP). Multer-fileFilter ist nur "fast reject"
    // anhand des client-gemeldeten MIME-Types; der echte Guard ist der
    // Magic-Byte-Check in validateUploadedFile.
    const allowed = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (allowed.includes(file.mimetype)) cb(null, true);
    else cb(new Error('Nur PDF, JPG, PNG, GIF oder WebP-Dateien sind erlaubt'));
  },
  limits: { fileSize: 25 * 1024 * 1024 },
});

router.get('/', authenticate, requirePermission('contracts:read'), contractController.getContracts);
router.post('/', authenticate, requirePermission('contracts:create'), contractController.createContract);

// Vertrags-Cockpit (muss VOR /:id stehen!)
router.get('/cockpit', authenticate, requirePermission('contracts:read'), contractController.getCockpit);

router.get('/:id', authenticate, requirePermission('contracts:read'), contractController.getContract);
router.put('/:id', authenticate, requirePermission('contracts:update'), contractController.updateContract);
router.delete('/:id', authenticate, requirePermission('contracts:delete'), contractController.deleteContract);

// Follow-up contract
router.post('/:id/follow-up', authenticate, requirePermission('contracts:create'), contractController.createFollowUp);

// VVL (Vertragsverlängerung beim selben Anbieter, vollständige Kopie + Datums-Berechnung)
router.post('/:id/renewal', authenticate, requirePermission('contracts:create'), contractController.createRenewal);

// Snooze (Vertrag zurückstellen)
router.patch('/:id/snooze', authenticate, requirePermission('contracts:update'), contractController.snoozeContract);

// Rechnungen (für alle Vertragstypen)
router.get('/:id/invoices', authenticate, requirePermission('contracts:read'), invoiceController.getInvoicesByContract);
router.post('/:id/invoices', authenticate, requirePermission('contracts:update'), invoiceController.addInvoiceByContract);

// Gutschriften (Subventionen) am Vertrag – Mitarbeiter/Admin (Controller
// blockt Portal-Token zusätzlich explizit).
router.get('/:contractId/credit-notes', authenticate, requirePermission('contracts:read'), creditNoteController.listByContract);
router.get('/:contractId/credit-notes/defaults', authenticate, requirePermission('contracts:read'), creditNoteController.formDefaults);
router.post('/:contractId/credit-notes', authenticate, requirePermission('contracts:update'), creditNoteController.create);

// Vertragsdokumente
router.get('/:id/documents', authenticate, requirePermission('contracts:read'), contractController.getContractDocuments);
router.post('/:id/documents', authenticate, requirePermission('contracts:update'), docUpload.single('file'), validateUploadedFile, contractController.uploadContractDocument);
router.delete('/:id/documents/:documentId', authenticate, requirePermission('contracts:update'), contractController.deleteContractDocument);

// Folgezähler
router.post('/:id/successor-meter', authenticate, requirePermission('contracts:update'), contractController.addSuccessorMeter);
router.delete('/:id/contract-meter/:contractMeterId', authenticate, requirePermission('contracts:update'), contractController.removeContractMeter);

// Get decrypted password
router.get('/:id/password', authenticate, requirePermission('contracts:read'), contractController.getContractPassword);

// Get decrypted SimCard PIN/PUK
router.get('/simcard/:simCardId/credentials', authenticate, requirePermission('contracts:read'), contractController.getSimCardCredentials);

// Get decrypted Internet password
router.get('/:id/internet-credentials', authenticate, requirePermission('contracts:read'), contractController.getInternetCredentials);

// Get decrypted SIP password
router.get('/phonenumber/:phoneNumberId/sip-credentials', authenticate, requirePermission('contracts:read'), contractController.getSipCredentials);

export default router;
