const express = require('express');
const router = express.Router();
const { getDbPool, isMockDB } = require('../config/db');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Ensure upload directory exists
const uploadDir = path.join(__dirname, '../uploads/agreements');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// Multer Storage Configuration
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + '-' + file.originalname.replace(/\s+/g, '-'));
  }
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit
});

// GET all agreements
router.get('/', async (req, res) => {
  try {
    if (isMockDB()) {
      return res.json({ success: true, data: [] });
    }
    const dbPool = getDbPool();
    const [agreements] = await dbPool.query(`
      SELECT a.*, c.name as customer_name 
      FROM agreements a 
      LEFT JOIN customers c ON a.customer_id = c.id
      ORDER BY a.created_at DESC
    `);
    res.json({ success: true, data: agreements });
  } catch (error) {
    console.error('Error fetching agreements:', error);
    res.status(500).json({ success: false, message: 'Server Error' });
  }
});

// POST create agreement
router.post('/', upload.array('files', 10), async (req, res) => {
  try {
    if (isMockDB()) {
      return res.status(400).json({ success: false, message: 'Mock DB not supported for this action' });
    }
    
    const dbPool = getDbPool();
    const { customer_id, start_date, end_date, condition_text, description, status } = req.body;
    
    // Process uploaded files
    const filePaths = req.files ? req.files.map(f => `/uploads/agreements/${f.filename}`) : [];
    const finalStatus = status || 'Pending';

    const [result] = await dbPool.query(
      `INSERT INTO agreements (customer_id, start_date, end_date, condition_text, description, status, file_paths) 
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [customer_id, start_date, end_date, condition_text, description, finalStatus, JSON.stringify(filePaths)]
    );

    res.json({ success: true, message: 'Agreement created successfully', data: { id: result.insertId } });
  } catch (error) {
    console.error('Error creating agreement:', error);
    res.status(500).json({ success: false, message: 'Server Error' });
  }
});

// PUT update agreement
router.put('/:id', upload.array('files', 10), async (req, res) => {
  try {
    const { id } = req.params;
    if (isMockDB()) return res.status(400).json({ success: false, message: 'Mock DB not supported' });
    
    const dbPool = getDbPool();
    const { customer_id, start_date, end_date, condition_text, description, status, existing_files } = req.body;
    const finalStatus = status || 'Pending';
    
    // Parse existing files from JSON string
    let parsedExistingFiles = [];
    if (existing_files) {
      try {
        parsedExistingFiles = JSON.parse(existing_files);
      } catch (e) {
        if (typeof existing_files === 'string') parsedExistingFiles = [existing_files];
      }
    }

    // New uploaded files
    const newFilePaths = req.files ? req.files.map(f => `/uploads/agreements/${f.filename}`) : [];
    
    // Combine old and new
    const finalFilePaths = [...parsedExistingFiles, ...newFilePaths];

    await dbPool.query(
      `UPDATE agreements SET 
        customer_id = ?, start_date = ?, end_date = ?, condition_text = ?, 
        description = ?, status = ?, file_paths = ? 
       WHERE id = ?`,
      [customer_id, start_date, end_date, condition_text, description, finalStatus, JSON.stringify(finalFilePaths), id]
    );

    res.json({ success: true, message: 'Agreement updated successfully' });
  } catch (error) {
    console.error('Error updating agreement:', error);
    res.status(500).json({ success: false, message: 'Server Error' });
  }
});

// DELETE agreement
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    if (isMockDB()) return res.status(400).json({ success: false, message: 'Mock DB not supported' });

    const dbPool = getDbPool();
    
    // Fetch the agreement to delete files (optional cleanup)
    const [agreements] = await dbPool.query('SELECT file_paths FROM agreements WHERE id = ?', [id]);
    if (agreements.length > 0) {
      let filePaths = [];
      try {
        if (agreements[0].file_paths) {
            filePaths = typeof agreements[0].file_paths === 'string' ? JSON.parse(agreements[0].file_paths) : agreements[0].file_paths;
        }
      } catch (e) {}
      
      filePaths.forEach(fp => {
        const fullPath = path.join(__dirname, '..', fp);
        if (fs.existsSync(fullPath)) {
          fs.unlinkSync(fullPath);
        }
      });
    }

    await dbPool.query('DELETE FROM agreements WHERE id = ?', [id]);
    res.json({ success: true, message: 'Agreement deleted successfully' });
  } catch (error) {
    console.error('Error deleting agreement:', error);
    res.status(500).json({ success: false, message: 'Server Error' });
  }
});

module.exports = router;
