const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 3001;

// CORS Configuration
const corsOptions = {
  origin: function (origin, callback) {
    console.log('🔍 Request origin:', origin);
    
    const allowedOrigins = [
      'http://localhost:3000',
      'http://localhost:3001',
      'https://api.muvietplus.net',
      'https://kthcdemo.muvietplus.net'
    ];
    
    if (!origin || allowedOrigins.includes(origin)) {
      console.log('✅ CORS allowed origin:', origin);
      callback(null, true);
    } else {
      console.log('🚫 CORS blocked origin:', origin);
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'],
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));
app.use(express.json());

// Test endpoint
app.get('/api/test', (req, res) => {
  console.log('📨 GET /api/test');
  console.log('  Origin:', req.headers.origin);
  console.log('  Referer:', req.headers.referer);
  
  res.json({
    success: true,
    message: 'CORS test successful!',
    timestamp: new Date().toISOString(),
    origin: req.headers.origin
  });
});

app.post('/api/test', (req, res) => {
  console.log('📨 POST /api/test');
  console.log('  Origin:', req.headers.origin);
  console.log('  Body:', req.body);
  
  res.json({
    success: true,
    message: 'POST test successful!',
    timestamp: new Date().toISOString(),
    origin: req.headers.origin,
    body: req.body
  });
});

// Health check
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: 'Server is running',
    timestamp: new Date().toISOString()
  });
});

app.listen(PORT, () => {
  console.log(`🚀 Test server đang chạy trên port ${PORT}`);
  console.log(`🌐 Truy cập: http://localhost:${PORT}`);
});
