const express = require('express');
const axios = require('axios');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '../frontend')));

// LiteAPI base configuration
const liteapi = axios.create({
  baseURL: 'https://api.liteapi.travel/v3.0',
  headers: {
    'X-API-Key': process.env.LITEAPI_KEY,
    'Content-Type': 'application/json'
  }
});

// Proxy routes to LiteAPI

// Search hotels by location
app.get('/api/hotels', async (req, res) => {
  try {
    const { city, lat, lng, radius, placeId, search } = req.query;
    
    const params = { limit: 20 };
    if (city) params.city = city;
    if (lat) params.lat = lat;
    if (lng) params.lng = lng;
    if (radius) params.radius = radius;
    if (placeId) params.placeId = placeId;
    if (search) params.search = search;
    
    const response = await liteapi.get('/data/hotels', { params });
    res.json(response.data);
  } catch (error) {
    console.error('Hotel search error:', error.response?.data || error.message);
    res.status(error.response?.status || 500).json({ 
      error: 'Failed to search hotels',
      details: error.response?.data || error.message 
    });
  }
});

// Get hotel rates & availability
app.post('/api/hotels/rates', async (req, res) => {
  try {
    const { hotelId, checkIn, checkOut, rooms, adults } = req.body;
    
    const response = await liteapi.post('/hotels/rates', {
      hotelId,
      checkIn,
      checkOut,
      rooms: rooms || 1,
      adults: adults || 2
    });
    
    res.json(response.data);
  } catch (error) {
    console.error('Rates error:', error.response?.data || error.message);
    res.status(error.response?.status || 500).json({ 
      error: 'Failed to get rates',
      details: error.response?.data || error.message 
    });
  }
});

// Search places/destinations
app.get('/api/places', async (req, res) => {
  try {
    const { search } = req.query;
    
    const response = await liteapi.get('/data/places', {
      params: { search, limit: 10 }
    });
    
    res.json(response.data);
  } catch (error) {
    console.error('Places search error:', error.response?.data || error.message);
    res.status(error.response?.status || 500).json({ 
      error: 'Failed to search places',
      details: error.response?.data || error.message 
    });
  }
});

// Get hotel details
app.get('/api/hotels/:hotelId', async (req, res) => {
  try {
    const { hotelId } = req.params;
    
    const response = await liteapi.get(`/data/hotels`, {
      params: { hotelIds: hotelId }
    });
    
    res.json(response.data);
  } catch (error) {
    console.error('Hotel details error:', error.response?.data || error.message);
    res.status(error.response?.status || 500).json({ 
      error: 'Failed to get hotel details',
      details: error.response?.data || error.message 
    });
  }
});

// Create booking
app.post('/api/bookings', async (req, res) => {
  try {
    const { rateId, guestDetails, paymentDetails } = req.body;
    
    const response = await liteapi.post('/bookings', {
      rateId,
      guest: guestDetails,
      payment: paymentDetails
    });
    
    res.json(response.data);
  } catch (error) {
    console.error('Booking error:', error.response?.data || error.message);
    res.status(error.response?.status || 500).json({ 
      error: 'Failed to create booking',
      details: error.response?.data || error.message 
    });
  }
});

// Serve frontend
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/index.html'));
});

app.get('/results', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/results.html'));
});

app.get('/hotel/:id', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/details.html'));
});

// Start server
app.listen(PORT, () => {
  console.log(`👻 GHOST TRAVEL server running on http://localhost:${PORT}`);
  console.log(`📍 API Key configured: ${process.env.LITEAPI_KEY ? '✅' : '❌ Missing!'}`);
});
