const express = require('express');
const cors = require('cors');
const config = require('./config/config');
const formRoutes = require('./routes/formRoutes');
const axios = require('axios');
const crypto = require('crypto');
const db = require('./lib/connection');
const helmet = require('helmet'); // Optional: for security headers

const app = express();
const PORT = config.port || 5000;

// Set allowed origins based on environment
const allowedOrigins = [
  'http://localhost:5173',
  'https://ugbowomegafair.com',
  'https://www.ugbowomegafair.com',
  'https://registration.ugbowomegafair.com'
];

const corsOptions = {
  origin: (origin, callback) => {
    // Allow requests with no origin (like mobile apps or curl)
    if (!origin || allowedOrigins.includes(origin)) {
      return callback(null, true);
    }
    return callback(new Error('Not allowed by CORS'));
  },
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization'],
};

app.use(cors(corsOptions));
app.use(helmet()); // Secure HTTP headers
app.use(express.json());
app.use('/uploads', express.static('uploads'));

// Routes
app.use('/api/form', formRoutes);

app.get('/', (req, res) => {
  console.log('GET / called');
  res.send('✅ Ugbowo Fair Backend is running.');
});

// Price map
const SLOT_PRICES = {
  mini: 40000,
  half: 80000,
  full: 150000
};

// Payment init
app.post('/api/paystack/init', async (req, res) => {
  console.log('➡️ POST /api/paystack/init received');
  console.log('Body:', req.body);

  const { email, metadata } = req.body;
  const slotOption = metadata?.slotOption;

  if (!SLOT_PRICES[slotOption]) {
    console.warn('❌ Invalid slot_option:', slotOption);
    return res.status(400).json({ error: 'Invalid slot option' });
  }

  const amountInKobo = SLOT_PRICES[slotOption] * 100;

  try {
    const response = await axios.post(
      'https://api.paystack.co/transaction/initialize',
      { email, amount: amountInKobo, metadata },
      {
        headers: {
          Authorization: `Bearer ${config.PAYSTACK_SECRET_KEY}`,
          'Content-Type': 'application/json',
        },
      }
    );

    console.log('✅ Paystack init success:', response.data.data.reference);

    res.json({
      authorization_url: response.data.data.authorization_url,
      reference: response.data.data.reference,
    });
  } catch (error) {
    console.error('❌ Paystack init failed:', error.message);
    res.status(500).json({ error: 'Payment initialization failed' });
  }
});

// Webhook
app.post(
  '/api/paystack/webhook',
  express.json({
    verify: (req, res, buf) => {
      req.rawBody = buf.toString();
    },
  }),
  async (req, res) => {
    console.log('📥 Webhook received');

    const hash = crypto
      .createHmac('sha512', config.PAYSTACK_SECRET_KEY)
      .update(req.rawBody)
      .digest('hex');

    if (hash !== req.headers['x-paystack-signature']) {
      console.warn('❌ Invalid webhook signature');
      return res.status(400).send('Invalid signature');
    }

    const event = req.body;
    console.log('📦 Event:', event.event);

    if (event.event === 'charge.success') {
      const metadata = event.data.metadata;

      const values = [
        metadata.firstName || metadata.first_name,
        metadata.surname || metadata.surName,
        metadata.businessName || metadata.business_name,
        metadata.cacRegistered || metadata.cac_registered,
        metadata.slotOption || metadata.slot_option,
      ];

      const query = `
        INSERT INTO registrations (first_name, surname, business_name, cac_registered, slot_option)
        VALUES (?, ?, ?, ?, ?)
      `;

      db.query(query, values, (err, result) => {
        if (err) {
          console.error('❌ DB error:', err);
        } else {
          console.log('✅ Registration saved. ID:', result.insertId);
        }
      });
    }

    res.sendStatus(200);
  }
);

// Optional: global error handler
app.use((err, req, res, next) => {
  console.error('🔥 Global error:', err.message);
  res.status(500).json({ error: 'Internal server error' });
});

app.listen(PORT, () => {
  console.log(`🚀 Server running on port ${PORT}`);
});
