const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

// Middleware to verify JWT token
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ success: false, message: 'Access token required' });
  }

  jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key-change-this-in-production', (err, user) => {
    if (err) {
      return res.status(403).json({ success: false, message: 'Invalid or expired token' });
    }
    req.user = user;
    next();
  });
};

// Helper function to determine zone from postcode
function getZoneFromPostcode(postcode) {
  if (!postcode) return null;
  
  const prefix = postcode.trim().toUpperCase().match(/^[A-Z]+/)?.[0];
  const number = postcode.trim().toUpperCase().match(/^[A-Z]+(\d+)/)?.[1];
  
  // Zone A: Manchester City Center (M1-M4, M15)
  if (prefix === 'M' && number) {
    const num = parseInt(number);
    if (num >= 1 && num <= 4) return 'zone-a';
    if (num === 15) return 'zone-a';
  }
  
  // Zone B: Greater Manchester (M5-M99, BL, OL, SK, WA, WN)
  if (prefix === 'M' && number && parseInt(number) >= 5) return 'zone-b';
  if (['BL', 'OL', 'SK', 'WA', 'WN'].includes(prefix)) return 'zone-b';
  
  // Zone C: Chester (CH)
  if (prefix === 'CH') return 'zone-c';
  
  // Zone D: Liverpool (L)
  if (prefix === 'L') return 'zone-d';
  
  return null;
}

// Get all pricing zone rules
router.get('/', authenticateToken, async (req, res) => {
  const db = req.app.locals.db;
  
  db.all('SELECT * FROM pricing_zones ORDER BY journey_type, from_zone, to_zone', [], (err, rows) => {
    if (err) {
      return res.json({ success: false, message: 'Database error', error: err.message });
    }
    res.json({ success: true, rules: rows });
  });
});

// Create or update pricing zone rule
router.post('/', authenticateToken, async (req, res) => {
  const db = req.app.locals.db;
  const { journey_type, from_zone, to_zone, vehicle_id, price } = req.body;
  
  // Check if rule exists
  db.get(
    'SELECT id FROM pricing_zones WHERE journey_type = ? AND from_zone = ? AND to_zone = ? AND vehicle_id = ?',
    [journey_type, from_zone, to_zone, vehicle_id],
    (err, row) => {
      if (err) {
        return res.json({ success: false, message: 'Database error', error: err.message });
      }
      
      if (row) {
        // Update existing rule
        db.run(
          'UPDATE pricing_zones SET price = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
          [price, row.id],
          function(err) {
            if (err) {
              return res.json({ success: false, message: 'Failed to update price', error: err.message });
            }
            res.json({ success: true, message: 'Price updated successfully', id: row.id });
          }
        );
      } else {
        // Insert new rule
        db.run(
          'INSERT INTO pricing_zones (journey_type, from_zone, to_zone, vehicle_id, price) VALUES (?, ?, ?, ?, ?)',
          [journey_type, from_zone, to_zone, vehicle_id, price],
          function(err) {
            if (err) {
              return res.json({ success: false, message: 'Failed to create price', error: err.message });
            }
            res.json({ success: true, message: 'Price created successfully', id: this.lastID });
          }
        );
      }
    }
  );
});

// Calculate price for a journey (public endpoint for booking page)
router.post('/calculate', async (req, res) => {
  const db = req.app.locals.db;
  const { journey_type, pickup_postcode, dropoff_postcode, vehicle_id } = req.body;
  
  // Determine zones from postcodes
  const fromZone = journey_type === 'airport-to-address' ? 'any-airport' : getZoneFromPostcode(pickup_postcode);
  const toZone = journey_type === 'address-to-airport' ? 'any-airport' : getZoneFromPostcode(dropoff_postcode);
  
  if (!fromZone || !toZone) {
    return res.json({ success: false, message: 'Invalid postcode or out of service area' });
  }
  
  // Lookup price in database
  db.get(
    'SELECT price FROM pricing_zones WHERE journey_type = ? AND from_zone = ? AND to_zone = ? AND vehicle_id = ?',
    [journey_type, fromZone, toZone, vehicle_id],
    (err, row) => {
      if (err) {
        return res.json({ success: false, message: 'Database error', error: err.message });
      }
      
      if (row) {
        res.json({ success: true, price: row.price, from_zone: fromZone, to_zone: toZone });
      } else {
        // Fallback to vehicle base price
        db.get('SELECT base_price FROM cms_vehicles WHERE id = ?', [vehicle_id], (err, vehicle) => {
          if (err || !vehicle) {
            return res.json({ success: false, message: 'Vehicle not found' });
          }
          res.json({ success: true, price: vehicle.base_price, from_zone: fromZone, to_zone: toZone, fallback: true });
        });
      }
    }
  );
});

module.exports = router;
