/**
 * Location Validator for Ash Transfer
 * 
 * Business Rules:
 * 1. Customer pickup OR dropoff must be in Greater Manchester, Chester, or Liverpool area
 * 2. ANY UK airport can be used for pickup or dropoff
 * 3. Cannot serve bookings where BOTH locations are outside the service area (unless one is a UK airport)
 */

// UK airports with their common names/codes
const UK_AIRPORTS = [
    // Major UK airports
    'manchester airport', 'man', 'ringway',
    'liverpool airport', 'ljla', 'john lennon',
    'heathrow', 'lhr', 'london heathrow',
    'gatwick', 'lgw', 'london gatwick',
    'stansted', 'stn', 'london stansted',
    'luton', 'ltn', 'london luton',
    'city airport', 'lcy', 'london city',
    'birmingham airport', 'bhx',
    'east midlands airport', 'ema',
    'leeds bradford', 'lba',
    'newcastle airport', 'ncl',
    'edinburgh airport', 'edi',
    'glasgow airport', 'gla',
    'aberdeen airport', 'abz',
    'belfast airport', 'bfs', 'bhd',
    'bristol airport', 'brs',
    'cardiff airport', 'cwr',
    'southampton airport', 'sou',
    'exeter airport', 'ext',
    'bournemouth airport', 'boh',
    'doncaster sheffield', 'dsa',
    'inverness airport', 'inv',
    'prestwick', 'pik',
    // Add common variations
    'airport', 'terminal'
];

// Service area postcodes and towns (Greater Manchester, Chester, Liverpool)
const SERVICE_AREA_POSTCODES = [
    // Greater Manchester postcodes
    'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9',
    'm11', 'm12', 'm13', 'm14', 'm15', 'm16', 'm17', 'm18', 'm19',
    'm20', 'm21', 'm22', 'm23', 'm24', 'm25', 'm26', 'm27', 'm28', 'm29',
    'm30', 'm31', 'm32', 'm33', 'm34', 'm35', 'm38', 'm40', 'm41', 'm43', 'm44', 'm45', 'm46', 'm50', 'm60', 'm90',
    'wn', // Wigan
    'bl', // Bolton
    'ol', // Oldham
    'sk', // Stockport
    'wa', // Warrington (partial)
    // Chester postcodes
    'ch1', 'ch2', 'ch3', 'ch4', 'ch65', 'ch66',
    // Liverpool postcodes
    'l1', 'l2', 'l3', 'l4', 'l5', 'l6', 'l7', 'l8', 'l9',
    'l10', 'l11', 'l12', 'l13', 'l14', 'l15', 'l16', 'l17', 'l18', 'l19',
    'l20', 'l21', 'l22', 'l23', 'l24', 'l25', 'l26', 'l27', 'l28', 'l29',
    'l30', 'l31', 'l32', 'l33', 'l34', 'l35', 'l36', 'l37', 'l38', 'l39', 'l40', 'l70', 'l75', 'l80'
];

const SERVICE_AREA_TOWNS = [
    // Greater Manchester
    'manchester', 'salford', 'stockport', 'bolton', 'bury', 'oldham', 
    'rochdale', 'wigan', 'trafford', 'altrincham', 'sale', 'urmston',
    'stretford', 'ashton-under-lyne', 'stalybridge', 'hyde', 'denton',
    'leigh', 'eccles', 'swinton', 'radcliffe', 'prestwich', 'whitefield',
    'middleton', 'failsworth', 'chadderton', 'shaw', 'heywood', 'ramsbottom',
    // Chester
    'chester', 'ellesmere port', 'neston', 'frodsham',
    // Liverpool
    'liverpool', 'bootle', 'crosby', 'formby', 'maghull', 'kirkby',
    'huyton', 'prescot', 'knowsley', 'halewood', 'speke', 'garston',
    'allerton', 'childwall', 'woolton', 'wavertree', 'mossley hill',
    'west derby', 'anfield', 'walton', 'aintree', 'fazakerley',
    'birkenhead', 'wallasey', 'bebington', 'heswall', 'wirral'
];

/**
 * Check if location string contains a UK airport
 * @param {string} location - Location string to check
 * @returns {boolean} - True if location is a UK airport
 */
function isUKAirport(location) {
    if (!location) return false;
    const normalized = location.toLowerCase().trim();
    
    return UK_AIRPORTS.some(airport => normalized.includes(airport));
}

/**
 * Check if location is within service area (Manchester, Chester, Liverpool)
 * @param {string} location - Location string or postcode to check
 * @returns {boolean} - True if location is in service area
 */
function isInServiceArea(location) {
    if (!location) return false;
    const normalized = location.toLowerCase().trim();
    
    // Check postcode patterns
    const postcodeMatch = normalized.match(/([a-z]{1,2}\d{1,2})/i);
    if (postcodeMatch) {
        const postcode = postcodeMatch[1].toLowerCase();
        if (SERVICE_AREA_POSTCODES.some(pc => postcode.startsWith(pc))) {
            return true;
        }
    }
    
    // Check town/city names
    return SERVICE_AREA_TOWNS.some(town => normalized.includes(town));
}

/**
 * Validate if a booking request meets location requirements
 * @param {string} pickup - Pickup location
 * @param {string} dropoff - Dropoff location
 * @returns {Object} - { valid: boolean, message: string, details: Object }
 */
function validateBookingLocations(pickup, dropoff) {
    if (!pickup || !dropoff) {
        return {
            valid: false,
            message: 'Both pickup and dropoff locations are required',
            details: { pickup: false, dropoff: false, airportInvolved: false }
        };
    }
    
    const pickupIsAirport = isUKAirport(pickup);
    const dropoffIsAirport = isUKAirport(dropoff);
    const pickupInArea = isInServiceArea(pickup);
    const dropoffInArea = isInServiceArea(dropoff);
    
    const airportInvolved = pickupIsAirport || dropoffIsAirport;
    const oneLocationInArea = pickupInArea || dropoffInArea;
    
    // Valid scenarios:
    // 1. Pickup in service area + any dropoff (including airports)
    // 2. Dropoff in service area + any pickup (including airports)
    // 3. Any UK airport + service area location
    
    if (airportInvolved && oneLocationInArea) {
        // Airport transfer with service area location
        return {
            valid: true,
            message: 'Valid airport transfer',
            details: {
                pickup: pickupIsAirport || pickupInArea,
                dropoff: dropoffIsAirport || dropoffInArea,
                airportInvolved: true
            }
        };
    }
    
    if (pickupInArea && dropoffInArea) {
        // Both locations in service area
        return {
            valid: true,
            message: 'Valid local transfer',
            details: {
                pickup: true,
                dropoff: true,
                airportInvolved: false
            }
        };
    }
    
    if (oneLocationInArea && !airportInvolved) {
        // One location in area, other is not airport - could be valid for some destinations
        return {
            valid: true,
            message: 'Transfer from/to service area',
            details: {
                pickup: pickupInArea,
                dropoff: dropoffInArea,
                airportInvolved: false
            }
        };
    }
    
    // Invalid scenario: Neither location in service area and no airport involved
    return {
        valid: false,
        message: 'Sorry, we only accept bookings where the pickup or dropoff is in the Greater Manchester, Chester, or Liverpool area. However, we do provide transfers to/from any UK airport.',
        details: {
            pickup: pickupInArea || pickupIsAirport,
            dropoff: dropoffInArea || dropoffIsAirport,
            airportInvolved: airportInvolved,
            suggestion: 'Please ensure at least one location is in Manchester, Chester, Liverpool, or any UK airport.'
        }
    };
}

/**
 * Get user-friendly validation message
 * @param {Object} validationResult - Result from validateBookingLocations
 * @returns {string} - User-friendly message
 */
function getValidationMessage(validationResult) {
    if (validationResult.valid) {
        return '';
    }
    
    return validationResult.message + '\n\nService Areas:\n' +
           '• Greater Manchester (all areas)\n' +
           '• Chester and surrounding areas\n' +
           '• Liverpool and Merseyside\n' +
           '• Any UK airport for collection or delivery\n\n' +
           'Contact us: +44 7860 261578';
}

module.exports = {
    isUKAirport,
    isInServiceArea,
    validateBookingLocations,
    getValidationMessage,
    UK_AIRPORTS,
    SERVICE_AREA_POSTCODES,
    SERVICE_AREA_TOWNS
};
