const express = require('express');
const cors = require('cors');
const path = require('path');
const bcrypt = require('bcryptjs');
const authMiddleware = require('./middleware/auth');
require('dotenv').config();

const { connectDB, getConnection } = require('./config/database');

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


const corsOptions = {
  origin: async (origin, callback) => {
    if (!origin) return callback(null, true);

    if (origin.includes('localhost') || origin.includes('127.0.0.1')) {
      return callback(null, true);
    }
    
    try {
      const connection = getConnection();
      const [sites] = await connection.execute(
        'SELECT domain FROM sites WHERE is_active = true'
      );
      
      const allowedDomains = [];

      sites.forEach(site => {
        allowedDomains.push(`https://${site.domain}`);
        allowedDomains.push(`http://${site.domain}`);
        allowedDomains.push(`https://www.${site.domain}`);
        allowedDomains.push(`http://www.${site.domain}`);
      });
      
      // Add admin panel domains (you can configure these)
      const adminDomains = [
        'admin.takipci-panel.com',
        'panel.takipci-panel.com'
      ];
      
      adminDomains.forEach(domain => {
        allowedDomains.push(`https://${domain}`);
        allowedDomains.push(`http://${domain}`);
      });
      
      // Check if origin is allowed
      const isAllowed = allowedDomains.some(domain => {
        const domainWithoutProtocol = domain.replace('https://', '').replace('http://', '');
        const originWithoutProtocol = origin.replace('https://', '').replace('http://', '');
        return originWithoutProtocol === domainWithoutProtocol;
      });
      
      if (isAllowed) {
        callback(null, true);
      } else {
        console.log(`CORS blocked origin: ${origin}`);
        callback(new Error('Bu domain CORS politikası tarafından izin verilmiyor'));
      }
    } catch (error) {
      console.error('CORS check error:', error);
      callback(new Error('CORS kontrolü başarısız'));
    }
  },
  credentials: true,
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Enhanced auth middleware for admin endpoints
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 - Admin authentication needed' 
    });
  }

  res.status(403).json({
    success: false,
    message: 'Invalid or expired token' 
  });
};

// Domain validation middleware for public endpoints
const validateDomain = async (req, res, next) => {
  try {
    // Skip validation for admin endpoints and health check
    if (req.path.includes('/admin') || req.path === '/sites' || req.path === '/platforms' || req.path === '/health') {
      return next();
    }

    const origin = req.headers.origin || req.headers.referer;
    const userAgent = req.headers['user-agent'] || '';
    
    // Allow requests from localhost during development
    if (origin && (origin.includes('localhost') || origin.includes('127.0.0.1'))) {
      return next();
    }
    
    // Block direct API access without proper origin
    if (!origin) {
      return res.status(403).json({
        success: false,
        message: 'Direct API access not allowed'
      });
    }
    
    // Validate origin against registered domains
    const connection = getConnection();
    const domain = new URL(origin).hostname;
    
    const [sites] = await connection.execute(
      'SELECT id FROM sites WHERE domain = ? OR domain = ?',
      [domain, `www.${domain}`]
    );
    
    if (sites.length === 0) {
      return res.status(403).json({
        success: false,
        message: 'Domain not authorized'
      });
    }
    
    next();
  } catch (error) {
    console.error('Domain validation error:', error);
    // On validation error, allow the request to proceed (fail open)
    next();
  }
};

// Apply domain validation to public endpoints only
const publicEndpoints = ['/api/blog-posts', '/api/blog-categories', '/api/products', '/api/categories', '/api/faqs', '/api/site-config'];
publicEndpoints.forEach(endpoint => {
  app.use(endpoint, validateDomain);
});

// Health check endpoint
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: 'Takipçi Panel API çalışıyor',
    timestamp: new Date().toISOString()
  });
});

// Auth routes
/*
app.post('/api/auth/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: 'Kullanıcı adı ve şifre gerekli'
      });
    }

    const connection = getConnection();
    const [rows] = await connection.execute(
      'SELECT id, username, email, password FROM admins WHERE username = ?',
      [username]
    );

    if (rows.length === 0) {
      return res.status(401).json({
        success: false,
        message: 'Geçersiz kullanıcı adı veya şifre'
      });
    }

    const admin = rows[0];
    const isPasswordValid = await bcrypt.compare(password, admin.password);

    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: 'Geçersiz kullanıcı adı veya şifre'
      });
    }

    res.json({
      success: true,
      data: {
        token: 'dummy-token-' + Date.now(),
        admin: { 
          id: admin.id, 
          username: admin.username,
          email: admin.email 
        }
      }
    });
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({
      success: false,
      message: 'Giriş işlemi sırasında hata oluştu'
    });
  }
});
*/

//Login Auth
app.use('/api/auth', require('./routes/auth'));

// Upload routes
app.use('/api/upload', require('./routes/upload'));

// Categories routes
app.get('/api/categories', async (req, res) => {
  try {
    const connection = getConnection();
    const { platform_id, parent_id, include_children } = req.query;
    
    let query = `
      SELECT c.*, p.name as platform_name, p.slug as platform_slug,
             parent.name as parent_name
      FROM categories c
      LEFT JOIN platforms p ON c.platform_id = p.id
      LEFT JOIN categories parent ON c.parent_id = parent.id
      WHERE c.is_active = true
    `;
    const params = [];

    if (platform_id) {
      query += ' AND c.platform_id = ?';
      params.push(platform_id);
    }

    if (parent_id !== undefined) {
      if (parent_id === 'null' || parent_id === null) {
        query += ' AND c.parent_id IS NULL';
      } else {
        query += ' AND c.parent_id = ?';
        params.push(parent_id);
      }
    }

    query += ' ORDER BY c.sort_order ASC, c.name ASC';

    const [rows] = await connection.execute(query, params);
    
    // If include_children is true, get subcategories for each category
    if (include_children === 'true') {
      for (let category of rows) {
        const [children] = await connection.execute(
          'SELECT * FROM categories WHERE parent_id = ? AND is_active = true ORDER BY sort_order ASC',
          [category.id]
        );
        category.children = children;
      }
    }
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('Categories fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Kategoriler getirilemedi'
    });
  }
});

app.post('/api/categories', async (req, res) => {
  try {
    const { platform_id, parent_id, name, slug, description, icon, color, sort_order } = req.body;
    
    if (!platform_id || !name || !slug) {
      return res.status(400).json({
        success: false,
        message: 'fuck off!'
      });
    }

    const connection = getConnection();
    
    const [result] = await connection.execute(
      'INSERT INTO categories (platform_id, parent_id, name, slug, description, icon, color, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [platform_id, parent_id || null, name, slug, description || null, icon || null, color || null, sort_order || 0, true]
    );
    
    const [newCategory] = await connection.execute(
      'SELECT * FROM categories WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json({
      success: true,
      data: newCategory[0],
      message: 'Kategori başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('Category create error:', error);
    res.status(500).json({
      success: false,
      message: 'Kategori oluşturulamadı'
    });
  }
});

app.put('/api/categories/:id', async (req, res) => {
  try {
    const categoryId = parseInt(req.params.id);
    const { platform_id, parent_id, name, slug, description, icon, color, sort_order, is_active } = req.body;
    
    const connection = getConnection();
    
    await connection.execute(
      'UPDATE categories SET platform_id = ?, parent_id = ?, name = ?, slug = ?, description = ?, icon = ?, color = ?, sort_order = ?, is_active = ? WHERE id = ?',
      [platform_id, parent_id || null, name, slug, description || null, icon || null, color || null, sort_order || 0, is_active !== undefined ? is_active : true, categoryId]
    );
    
    const [updatedCategory] = await connection.execute(
      'SELECT * FROM categories WHERE id = ?',
      [categoryId]
    );
    
    res.json({
      success: true,
      data: updatedCategory[0],
      message: 'Kategori başarıyla güncellendi'
    });
  } catch (error) {
    console.error('Category update error:', error);
    res.status(500).json({
      success: false,
      message: 'Kategori güncellenemedi'
    });
  }
});

app.delete('/api/categories/:id', async (req, res) => {
  try {
    const categoryId = parseInt(req.params.id);
    const connection = getConnection();
    
    // Check if category has subcategories
    const [subcategories] = await connection.execute(
      'SELECT COUNT(*) as count FROM categories WHERE parent_id = ? AND is_active = true',
      [categoryId]
    );
    
    if (subcategories[0].count > 0) {
      return res.status(400).json({
        success: false,
        message: 'Bu kategorinin alt kategorileri var. Önce alt kategorileri silin.'
      });
    }
    
    // Check if category has products
    const [products] = await connection.execute(
      'SELECT COUNT(*) as count FROM products WHERE category_id = ? AND is_active = true',
      [categoryId]
    );
    
    if (products[0].count > 0) {
      return res.status(400).json({
        success: false,
        message: 'Bu kategoriye ait ürünler var. Önce ürünleri silin veya başka kategoriye taşıyın.'
      });
    }
    
    await connection.execute(
      'DELETE FROM categories WHERE id = ?',
      [categoryId]
    );
    
    res.json({
      success: true,
      message: 'Kategori başarıyla silindi'
    });
  } catch (error) {
    console.error('Category delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Kategori silinemedi'
    });
  }
});

// Products routes
app.get('/api/products', async (req, res) => {
  try {
    const connection = getConnection();
    const { category_id, platform_id } = req.query;
    
    let query = `
      SELECT p.*, c.name as category_name, c.platform_id,
             pl.name as platform_name, pl.icon as platform_icon
      FROM products p
      LEFT JOIN categories c ON p.category_id = c.id
      LEFT JOIN platforms pl ON c.platform_id = pl.id
      WHERE p.is_active = true
    `;
    const params = [];

    if (category_id) {
      query += ' AND p.category_id = ?';
      params.push(category_id);
    }

    if (platform_id) {
      query += ' AND c.platform_id = ?';
      params.push(platform_id);
    }

    query += ' ORDER BY p.sort_order ASC, p.name ASC';

    const [rows] = await connection.execute(query, params);
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('Products fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Ürünler getirilemedi'
    });
  }
});

app.post('/api/products', async (req, res) => {
  try {
    const { category_id, name, description, quantity, original_price, sale_price, discount_percentage, sort_order, is_active } = req.body;
    
    if (!category_id || !name || !quantity || !original_price || !sale_price) {
      return res.status(400).json({
        success: false,
        message: 'Kategori, ürün adı, miktar, orijinal fiyat ve satış fiyatı gerekli'
      });
    }

    const connection = getConnection();
    
    const [result] = await connection.execute(
      'INSERT INTO products (category_id, name, description, quantity, original_price, sale_price, discount_percentage, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [category_id, name, description || null, parseInt(quantity), parseFloat(original_price), parseFloat(sale_price), parseInt(discount_percentage) || 0, parseInt(sort_order) || 0, is_active !== undefined ? is_active : true]
    );
    
    const [newProduct] = await connection.execute(
      'SELECT * FROM products WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json({
      success: true,
      data: newProduct[0],
      message: 'Ürün başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('Product create error:', error);
    res.status(500).json({
      success: false,
      message: 'Ürün oluşturulamadı'
    });
  }
});

app.put('/api/products/:id', async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    const { category_id, name, description, quantity, original_price, sale_price, discount_percentage, sort_order, is_active } = req.body;
    
    const connection = getConnection();
    
    await connection.execute(
      'UPDATE products SET category_id = ?, name = ?, description = ?, quantity = ?, original_price = ?, sale_price = ?, discount_percentage = ?, sort_order = ?, is_active = ? WHERE id = ?',
      [category_id, name, description || null, parseInt(quantity), parseFloat(original_price), parseFloat(sale_price), parseInt(discount_percentage) || 0, parseInt(sort_order) || 0, is_active !== undefined ? is_active : true, productId]
    );
    
    const [updatedProduct] = await connection.execute(
      'SELECT * FROM products WHERE id = ?',
      [productId]
    );
    
    res.json({
      success: true,
      data: updatedProduct[0],
      message: 'Ürün başarıyla güncellendi'
    });
  } catch (error) {
    console.error('Product update error:', error);
    res.status(500).json({
      success: false,
      message: 'Ürün güncellenemedi'
    });
  }
});

app.delete('/api/products/:id', async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    const connection = getConnection();
    
    await connection.execute(
      'DELETE FROM products WHERE id = ?',
      [productId]
    );
    
    res.json({
      success: true,
      message: 'Ürün başarıyla silindi'
    });
  } catch (error) {
    console.error('Product delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Ürün silinemedi'
    });
  }
});

// Sites routes
app.get('/api/sites', async (req, res) => {
  try {
    const connection = getConnection();
    const [sites] = await connection.execute(
      'SELECT * FROM sites ORDER BY name ASC'
    );
    
    res.json({
      success: true,
      data: sites
    });
  } catch (error) {
    console.error('Sites fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Siteler getirilemedi'
    });
  }
});

app.post('/api/sites',authMiddleware, async (req, res) => {
  try {
    const { 
      name, domain, slug, title, description, logo, favicon,
      primary_color, secondary_color, accent_color, background_color, text_color, font_family,
      meta_keywords, meta_description, google_analytics, facebook_pixel,
      custom_css, custom_js, seo_content, mascot_image,hero_background_image, is_active, payment_callback_url,is_maintenance, maintenance_message
    } = req.body;
    
    if (!name || !domain || !slug) {
      return res.status(400).json({
        success: false,
        message: 'Site adı, domain ve slug gerekli'
      });
    }

    const connection = getConnection();

    const [result] = await connection.execute(
      `INSERT INTO sites (
        name, domain, slug, title, description, logo, favicon,
        primary_color, secondary_color, accent_color, background_color, text_color, font_family,
        meta_keywords, meta_description, google_analytics, facebook_pixel,
        custom_css, custom_js, seo_content, mascot_image, hero_background_image, is_active,
        payment_callback_url, is_maintenance, maintenance_message
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        name, domain, slug, title || null, description || null, logo || null, favicon || null,
        primary_color || '#6366F1', secondary_color || '#F59E0B', accent_color || '#10B981', 
        background_color || '#F9FAFB', text_color || '#111827', font_family || 'Inter, sans-serif',
        meta_keywords || null, meta_description || null, google_analytics || null, facebook_pixel || null,
        custom_css || null, custom_js || null, seo_content || null, mascot_image || null ,hero_background_image || null,
        is_active !== undefined ? is_active : true,payment_callback_url || null, is_maintenance !== undefined ? is_maintenance : false,
        maintenance_message || null
      ]
    );
    
    const [newSite] = await connection.execute(
      'SELECT * FROM sites WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json({
      success: true,
      data: newSite[0],
      message: 'Site başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('Site create error:', error);
    res.status(500).json({
      success: false,
      message: 'Site oluşturulamadı'
    });
  }
});

app.put('/api/sites/:id',authMiddleware, async (req, res) => {
  try {
    //console.log("data:",req.body);
    const siteId = parseInt(req.params.id);
    const { 
      name, domain, slug, title, description, logo, favicon,
      primary_color, secondary_color, accent_color, background_color, text_color, font_family,
      meta_keywords, meta_description, google_analytics, facebook_pixel,
      custom_css, custom_js, seo_content, is_active,payment_callback_url, is_maintenance, maintenance_message ,hero_background_image,mascot_image
    } = req.body;
    
    const connection = getConnection();
    
    await connection.execute(
      `UPDATE sites SET 
        name = ?, domain = ?, slug = ?, title = ?, description = ?, logo = ?, favicon = ?,
        primary_color = ?, secondary_color = ?, accent_color = ?, background_color = ?, text_color = ?, font_family = ?,
        meta_keywords = ?, meta_description = ?, google_analytics = ?, facebook_pixel = ?,
        custom_css = ?, custom_js = ?, seo_content = ?, is_active = ?,payment_callback_url=?, is_maintenance = ?, maintenance_message = ?,hero_background_image=?,mascot_image=?
       WHERE id = ?`,
      [
        name, domain, slug, title || null, description || null, logo || null, favicon || null,
        primary_color || '#6366F1', secondary_color || '#F59E0B', accent_color || '#10B981', 
        background_color || '#F9FAFB', text_color || '#111827', font_family || 'Inter, sans-serif',
        meta_keywords || null, meta_description || null, google_analytics || null, facebook_pixel || null,
        custom_css || null, custom_js || null, seo_content || null, is_active !== undefined ? is_active : true,payment_callback_url || null ,
        is_maintenance !== undefined ? is_maintenance : false, maintenance_message || null,hero_background_image || null,mascot_image || null,
        siteId
      ]
    );
    
    const [updatedSite] = await connection.execute(
      'SELECT * FROM sites WHERE id = ?',
      [siteId]
    );
    
    res.json({
      success: true,
      data: updatedSite[0],
      message: 'Site başarıyla güncellendi'
    });
  } catch (error) {
    console.error('Site update error:', error);
    res.status(500).json({
      success: false,
      message: 'Site güncellenemedi'
    });
  }
});

app.delete('/api/sites/:id',authMiddleware, async (req, res) => {
  try {
    const siteId = parseInt(req.params.id);
    const connection = getConnection();
    
    await connection.execute(
      'DELETE FROM sites WHERE id = ?',
      [siteId]
    );
    
    res.json({
      success: true,
      message: 'Site başarıyla silindi'
    });
  } catch (error) {
    console.error('Site delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Site silinemedi'
    });
  }
});

// FAQs routes
app.get('/api/faqs', async (req, res) => {
  try {
    const { site_id } = req.query;
    const connection = getConnection();
    
    let query = 'SELECT * FROM faqs WHERE is_active = true';
    const params = [];
    
    if (site_id) {
      query += ' AND site_id = ?';
      params.push(site_id);
    }
    
    query += ' ORDER BY sort_order ASC, id ASC';
    
    const [rows] = await connection.execute(query, params);
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('FAQs fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'SSS verileri getirilemedi'
    });
  }
});

app.post('/api/faqs', async (req, res) => {
  try {
    const { site_id, question, answer, sort_order } = req.body;
    
    if (!site_id || !question || !answer) {
      return res.status(400).json({
        success: false,
        message: 'Site ID, soru ve cevap gerekli'
      });
    }

    const connection = getConnection();
    
    const [result] = await connection.execute(
      'INSERT INTO faqs (site_id, question, answer, sort_order, is_active) VALUES (?, ?, ?, ?, ?)',
      [site_id, question, answer, sort_order || 0, true]
    );
    
    const [newFaq] = await connection.execute(
      'SELECT * FROM faqs WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json({
      success: true,
      data: newFaq[0],
      message: 'SSS başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('FAQ create error:', error);
    res.status(500).json({
      success: false,
      message: 'SSS oluşturulamadı'
    });
  }
});

app.put('/api/faqs/:id', async (req, res) => {
  try {
    const faqId = parseInt(req.params.id);
    const { question, answer, sort_order, is_active } = req.body;
    
    const connection = getConnection();
    
    await connection.execute(
      'UPDATE faqs SET question = ?, answer = ?, sort_order = ?, is_active = ? WHERE id = ?',
      [question, answer, sort_order || 0, is_active !== undefined ? is_active : true, faqId]
    );
    
    const [updatedFaq] = await connection.execute(
      'SELECT * FROM faqs WHERE id = ?',
      [faqId]
    );
    
    res.json({
      success: true,
      data: updatedFaq[0],
      message: 'SSS başarıyla güncellendi'
    });
  } catch (error) {
    console.error('FAQ update error:', error);
    res.status(500).json({
      success: false,
      message: 'SSS güncellenemedi'
    });
  }
});

app.delete('/api/faqs/:id', async (req, res) => {
  try {
    const faqId = parseInt(req.params.id);
    const connection = getConnection();
    
    await connection.execute(
      'DELETE FROM faqs WHERE id = ?',
      [faqId]
    );
    
    res.json({
      success: true,
      message: 'SSS başarıyla silindi'
    });
  } catch (error) {
    console.error('FAQ delete error:', error);
    res.status(500).json({
      success: false,
      message: 'SSS silinemedi'
    });
  }
});

// Get site configuration by domain (for frontend sites)
app.get('/api/site-config', async (req, res) => {
  try {
    const { domain } = req.query;
    
    if (!domain) {
      return res.status(400).json({
        success: false,
        message: 'Domain parametresi gerekli'
      });
    }

    const connection = getConnection();
    const [sites] = await connection.execute(
      'SELECT * FROM sites WHERE domain = ? AND is_active = true',
      [domain]
    );
    
    if (sites.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Site bulunamadı veya aktif değil'
      });
    }

    const site = sites[0];
    
    // Only return necessary frontend configuration
    const config = {
      id: site.id,
      name: site.name,
      domain: site.domain,
      title: site.title,
      description: site.description,
      logo: site.logo,
      favicon: site.favicon,
      primary_color: site.primary_color,
      secondary_color: site.secondary_color,
      accent_color: site.accent_color,
      background_color: site.background_color,
      text_color: site.text_color,
      font_family: site.font_family,
      meta_keywords: site.meta_keywords,
      meta_description: site.meta_description,
      google_analytics: site.google_analytics,
      facebook_pixel: site.facebook_pixel,
      custom_css: site.custom_css,
      mascot_image:site.mascot_image,
      hero_background_image:site.hero_background_image,
      custom_js: site.custom_js,
      payment_callback_url:site.payment_callback_url,
      seo_content: site.seo_content,
      is_maintenance: site.is_maintenance,
      maintenance_message: site.maintenance_message
    };
    
    res.json({
      success: true,
      data: config
    });
  } catch (error) {
    console.error('Site config fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Site konfigürasyonu getirilemedi'
    });
  }
});

// Blog categories routes
app.get('/api/blog-categories', async (req, res) => {
  try {
    const { site_id } = req.query;
    const connection = getConnection();
    
    let query = `
      SELECT bc.*, s.name as site_name, s.domain as site_domain
      FROM blog_categories bc
      LEFT JOIN sites s ON bc.site_id = s.id
      WHERE 1=1
    `;
    const params = [];
    
    if (site_id) {
      query += ' AND bc.site_id = ?';
      params.push(site_id);
    }
    
    query += ' ORDER BY bc.name ASC';
    
    const [rows] = await connection.execute(query, params);
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('Blog categories fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog kategorileri getirilemedi'
    });
  }
});

app.post('/api/blog-categories',authMiddleware, async (req, res) => {
  try {
    const { site_id, name, slug, description } = req.body;
    
    if (!site_id || !name || !slug) {
      return res.status(400).json({
        success: false,
        message: 'Site ID, kategori adı ve slug gerekli'
      });
    }

    const connection = getConnection();
    
    const [result] = await connection.execute(
      'INSERT INTO blog_categories (site_id, name, slug, description) VALUES (?, ?, ?, ?)',
      [site_id, name, slug, description || null]
    );
    
    const [newCategory] = await connection.execute(
      'SELECT * FROM blog_categories WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json({
      success: true,
      data: newCategory[0],
      message: 'Blog kategorisi başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('Blog category create error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog kategorisi oluşturulamadı'
    });
  }
});

app.put('/api/blog-categories/:id', authMiddleware, async (req, res) => {
  try {
    const categoryId = parseInt(req.params.id);
    const { name, slug, description } = req.body;
    
    const connection = getConnection();
    
    await connection.execute(
      'UPDATE blog_categories SET name = ?, slug = ?, description = ? WHERE id = ?',
      [name, slug, description || null, categoryId]
    );
    
    const [updatedCategory] = await connection.execute(
      'SELECT * FROM blog_categories WHERE id = ?',
      [categoryId]
    );
    
    res.json({
      success: true,
      data: updatedCategory[0],
      message: 'Blog kategorisi başarıyla güncellendi'
    });
  } catch (error) {
    console.error('Blog category update error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog kategorisi güncellenemedi'
    });
  }
});

app.delete('/api/blog-categories/:id', authMiddleware, async (req, res) => {
  try {
    const categoryId = parseInt(req.params.id);
    const connection = getConnection();
    
    await connection.execute(
      'DELETE FROM blog_categories WHERE id = ?',
      [categoryId]
    );
    
    res.json({
      success: true,
      message: 'Blog kategorisi başarıyla silindi'
    });
  } catch (error) {
    console.error('Blog category delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog kategorisi silinemedi'
    });
  }
});

// Blog posts routes
app.get('/api/blog-posts', async (req, res) => {
  try {
    const { site_id, category_id, limit, offset } = req.query;
    const connection = getConnection();
    
    let query = `
      SELECT bp.*, bc.name as category_name, bc.slug as category_slug,
             s.name as site_name, s.domain as site_domain
      FROM blog_posts bp
      LEFT JOIN blog_categories bc ON bp.category_id = bc.id
      LEFT JOIN sites s ON bp.site_id = s.id
      WHERE bp.is_published = true
    `;
    const params = [];
    
    if (site_id) {
      query += ' AND bp.site_id = ?';
      params.push(site_id);
    }
    
    if (category_id) {
      query += ' AND bp.category_id = ?';
      params.push(category_id);
    }
    
    query += ' ORDER BY bp.created_at DESC';
    
    if (limit) {
      query += ' LIMIT ?';
      params.push(parseInt(limit));
      
      if (offset) {
        query += ' OFFSET ?';
        params.push(parseInt(offset));
      }
    }
    
    const [rows] = await connection.execute(query, params);
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('Blog posts fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog yazıları getirilemedi'
    });
  }
});

app.get('/api/blog-posts/:id', async (req, res) => {
  try {
    const postId = parseInt(req.params.id);
    const connection = getConnection();
    
    const [rows] = await connection.execute(
      `SELECT bp.*, s.name as site_name, s.domain as site_domain
       FROM blog_posts bp
       LEFT JOIN sites s ON bp.site_id = s.id
       WHERE bp.id = ? AND bp.is_active = true`,
      [postId]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Blog yazısı bulunamadı'
      });
    }
    
    res.json({
      success: true,
      data: rows[0]
    });
  } catch (error) {
    console.error('Blog post fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog yazısı getirilemedi'
    });
  }
});

app.post('/api/blog-posts', authMiddleware,async (req, res) => {
  try {
    const { site_id, category_id, title, slug, content, excerpt, featured_image, meta_title, meta_description, tags, is_featured } = req.body;
    
    if (!site_id || !title || !slug || !content) {
      return res.status(400).json({
        success: false,
        message: 'Site ID, başlık, slug ve içerik gerekli'
      });
    }

    const connection = getConnection();
    
    const [result] = await connection.execute(
      `INSERT INTO blog_posts (
        site_id, category_id, title, slug, content, excerpt, featured_image, 
        meta_title, meta_description, tags, is_featured, is_published
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        site_id, category_id || null, title, slug, content, excerpt || null, featured_image || null,
        meta_title || null, meta_description || null, tags || null, 
        is_featured !== undefined ? is_featured : false, true
      ]
    );
    
    const [newPost] = await connection.execute(
      'SELECT * FROM blog_posts WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json({
      success: true,
      data: newPost[0],
      message: 'Blog yazısı başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('Blog post create error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog yazısı oluşturulamadı'
    });
  }
});

app.put('/api/blog-posts/:id',authMiddleware, async (req, res) => {
  try {
    const postId = parseInt(req.params.id);
    const { category_id, title, slug, content, excerpt, featured_image, meta_title, meta_description, tags, is_featured, is_published } = req.body;
    
    const connection = getConnection();
    
    await connection.execute(
      `UPDATE blog_posts SET 
        category_id = ?, title = ?, slug = ?, content = ?, excerpt = ?, featured_image = ?,
        meta_title = ?, meta_description = ?, tags = ?, is_featured = ?, is_published = ?,
        updated_at = CURRENT_TIMESTAMP
       WHERE id = ?`,
      [
        category_id || null, title, slug, content, excerpt || null, featured_image || null,
        meta_title || null, meta_description || null, tags || null,
        is_featured !== undefined ? is_featured : false,
        is_published !== undefined ? is_published : true,
        postId
      ]
    );
    
    const [updatedPost] = await connection.execute(
      'SELECT * FROM blog_posts WHERE id = ?',
      [postId]
    );
    
    res.json({
      success: true,
      data: updatedPost[0],
      message: 'Blog yazısı başarıyla güncellendi'
    });
  } catch (error) {
    console.error('Blog post update error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog yazısı güncellenemedi'
    });
  }
});

app.delete('/api/blog-posts/:id',authMiddleware, async (req, res) => {
  try {
    const postId = parseInt(req.params.id);
    const connection = getConnection();
    
    await connection.execute(
      'DELETE FROM blog_posts WHERE id = ?',
      [postId]
    );
    
    res.json({
      success: true,
      message: 'Blog yazısı başarıyla silindi'
    });
  } catch (error) {
    console.error('Blog post delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog yazısı silinemedi'
    });
  }
});

// Get blog posts by slug (for frontend)
app.get('/api/blog-posts/slug/:slug', async (req, res) => {
  try {
    const { slug } = req.params;
    const { site_id } = req.query;
    const connection = getConnection();
    
    let query = `
      SELECT bp.*, s.name as site_name, s.domain as site_domain
      FROM blog_posts bp
      LEFT JOIN sites s ON bp.site_id = s.id
      WHERE bp.slug = ? AND bp.is_published = true
    `;
    const params = [slug];
    
    if (site_id) {
      query += ' AND bp.site_id = ?';
      params.push(site_id);
    }
    
    const [rows] = await connection.execute(query, params);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Blog yazısı bulunamadı'
      });
    }
    
    res.json({
      success: true,
      data: rows[0]
    });
  } catch (error) {
    console.error('Blog post by slug fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Blog yazısı getirilemedi'
    });
  }
});

// Platforms routes
app.get('/api/platforms', async (req, res) => {
  try {
    const connection = getConnection();
    const [platforms] = await connection.execute(
      'SELECT * FROM platforms WHERE is_active = true ORDER BY sort_order ASC, name ASC'
    );
    
    res.json({
      success: true,
      data: platforms
    });
  } catch (error) {
    console.error('Platforms fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Platformlar getirilemedi'
    });
  }
});

app.post('/api/platforms',authMiddleware, async (req, res) => {
  try {
    console.log("Authorization header:", req.headers['authorization']);
    const { name, slug, icon, color, sort_order } = req.body;
    
    if (!name || !slug) {
      return res.status(400).json({
        success: false,
        message: 'Platform adı ve slug gerekli'
      });
    }

    const connection = getConnection();
    
    const [result] = await connection.execute(
      'INSERT INTO platforms (name, slug, icon, color, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?)',
      [name, slug, icon || null, color || null, sort_order || 0, true]
    );
    
    const [newPlatform] = await connection.execute(
      'SELECT * FROM platforms WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json({
      success: true,
      data: newPlatform[0],
      message: 'Platform başarıyla oluşturuldu'
    });
  } catch (error) {
    console.error('Platform create error:', error);
    res.status(500).json({
      success: false,
      message: 'Platform oluşturulamadı'
    });
  }
});

app.put('/api/platforms/:id',authMiddleware, async (req, res) => {
  try {
    const platformId = parseInt(req.params.id);
    const { name, slug, icon, color, sort_order, is_active } = req.body;
    
    const connection = getConnection();
    
    await connection.execute(
      'UPDATE platforms SET name = ?, slug = ?, icon = ?, color = ?, sort_order = ?, is_active = ? WHERE id = ?',
      [name, slug, icon || null, color || null, sort_order || 0, is_active !== undefined ? is_active : true, platformId]
    );
    
    const [updatedPlatform] = await connection.execute(
      'SELECT * FROM platforms WHERE id = ?',
      [platformId]
    );
    
    res.json({
      success: true,
      data: updatedPlatform[0],
      message: 'Platform başarıyla güncellendi'
    });
  } catch (error) {
    console.error('Platform update error:', error);
    res.status(500).json({
      success: false,
      message: 'Platform güncellenemedi'
    });
  }
});

app.delete('/api/platforms/:id' ,authMiddleware, async (req, res) => {
  try {
    const platformId = parseInt(req.params.id);
    const connection = getConnection();
    
    // Start transaction for cascade delete
    await connection.query('START TRANSACTION');
    
    try {
      // Get categories that belong to this platform
      const [categories] = await connection.execute(
        'SELECT id FROM categories WHERE platform_id = ?',
        [platformId]
      );
      
      if (categories.length > 0) {
        const categoryIds = categories.map(cat => cat.id);
        const placeholders = categoryIds.map(() => '?').join(',');
        
        // Delete products first (they reference categories)
        await connection.execute(
          `DELETE FROM products WHERE category_id IN (${placeholders})`,
          categoryIds
        );
        
        // Delete all categories (including child categories due to foreign key cascade)
        await connection.execute(
          'DELETE FROM categories WHERE platform_id = ?',
          [platformId]
        );
      }
      
      // Finally delete the platform
      await connection.execute(
        'DELETE FROM platforms WHERE id = ?',
        [platformId]
      );
      
      // Commit transaction
      await connection.query('COMMIT');
      
      res.json({
        success: true,
        message: 'Platform ve ilgili tüm kategoriler/ürünler başarıyla silindi'
      });
      
    } catch (error) {
      // Rollback transaction on error
      await connection.query('ROLLBACK');
      throw error;
    }
    
  } catch (error) {
    console.error('Platform delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Platform silinemedi'
    });
  }
});

// Public endpoint - Get FAQs for category/product
app.get('/api/public/product-faqs', async (req, res) => {
  try {
    const { site_id, category_id, product_id } = req.query;
    
    if (!site_id) {
      return res.status(400).json({ 
        success: false, 
        message: 'site_id gerekli' 
      });
    }

    let query = `
      SELECT id, question, answer, sort_order 
      FROM product_faqs 
      WHERE site_id = ? AND is_active = true
    `;
    let params = [site_id];

    if (product_id) {
      query += ` AND (product_id = ? OR (product_id IS NULL AND category_id = ?))`;
      params.push(product_id, category_id);
    } else if (category_id) {
      query += ` AND (category_id = ? OR category_id IS NULL)`;
      params.push(category_id);
    } else {
      query += ` AND category_id IS NULL AND product_id IS NULL`;
    }

    query += ` ORDER BY sort_order ASC, id ASC`;

    const connection = getConnection();
    const [faqs] = await connection.execute(query, params);

    res.json({ 
      success: true, 
      data: faqs 
    });
  } catch (error) {
    console.error('Product FAQs getirme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

// Public endpoint - Get Customer Reviews for category/product
app.get('/api/public/customer-reviews', async (req, res) => {
  try {
    const { site_id, category_id, product_id } = req.query;
    
    if (!site_id) {
      return res.status(400).json({ 
        success: false, 
        message: 'site_id gerekli' 
      });
    }

    let query = `
      SELECT id, customer_name, customer_profession, review_text, rating, sort_order 
      FROM customer_reviews 
      WHERE site_id = ? AND is_active = true
    `;
    let params = [site_id];

    if (product_id) {
      query += ` AND (product_id = ? OR (product_id IS NULL AND category_id = ?))`;
      params.push(product_id, category_id);
    } else if (category_id) {
      query += ` AND (category_id = ? OR category_id IS NULL)`;
      params.push(category_id);
    } else {
      query += ` AND category_id IS NULL AND product_id IS NULL`;
    }

    query += ` ORDER BY sort_order ASC, id ASC`;

    const connection = getConnection();
    const [reviews] = await connection.execute(query, params);

    res.json({ 
      success: true, 
      data: reviews 
    });
  } catch (error) {
    console.error('Customer Reviews getirme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

// Admin endpoints for FAQ management
app.get('/api/admin/product-faqs',authMiddleware, async (req, res) => {
  try {
    const { site_id, category_id, product_id } = req.query;
    
    let query = `
      SELECT pf.*, s.name as site_name, c.name as category_name, p.name as product_name
      FROM product_faqs pf
      LEFT JOIN sites s ON pf.site_id = s.id
      LEFT JOIN categories c ON pf.category_id = c.id
      LEFT JOIN products p ON pf.product_id = p.id
      WHERE 1=1
    `;
    let params = [];

    if (site_id) {
      query += ` AND pf.site_id = ?`;
      params.push(site_id);
    }
    if (category_id) {
      query += ` AND pf.category_id = ?`;
      params.push(category_id);
    }
    if (product_id) {
      query += ` AND pf.product_id = ?`;
      params.push(product_id);
    }

    query += ` ORDER BY pf.sort_order ASC, pf.id ASC`;

    const connection = getConnection();
    const [faqs] = await connection.execute(query, params);

    res.json({ 
      success: true, 
      data: faqs 
    });
  } catch (error) {
    console.error('Admin product FAQs getirme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: `Sunucu hatası: ${error}`
    });
  }
});

// Admin endpoints for Customer Reviews management
app.get('/api/admin/customer-reviews',authMiddleware, async (req, res) => {
  try {
    const { site_id, category_id, product_id } = req.query;
    
    let query = `
      SELECT cr.*, s.name as site_name, c.name as category_name, p.name as product_name
      FROM customer_reviews cr
      LEFT JOIN sites s ON cr.site_id = s.id
      LEFT JOIN categories c ON cr.category_id = c.id
      LEFT JOIN products p ON cr.product_id = p.id
      WHERE 1=1
    `;
    let params = [];

    if (site_id) {
      query += ` AND cr.site_id = ?`;
      params.push(site_id);
    }
    if (category_id) {
      query += ` AND cr.category_id = ?`;
      params.push(category_id);
    }
    if (product_id) {
      query += ` AND cr.product_id = ?`;
      params.push(product_id);
    }

    query += ` ORDER BY cr.sort_order ASC, cr.id ASC`;

    const connection = getConnection();
    const [reviews] = await connection.execute(query, params);

    res.json({ 
      success: true, 
      data: reviews 
    });
  } catch (error) {
    console.error('Admin customer reviews getirme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: `Sunucu hatası: ${error}`
    });
  }
});

app.post('/api/admin/product-faqs', authMiddleware ,async (req, res) => {
  try {
    console.log('Admin FAQ create request body:', req.body);
    console.log(req);
    console.log('Data types:', {
      site_id: typeof req.body.site_id,
      category_id: typeof req.body.category_id,
      product_id: typeof req.body.product_id,
      question: typeof req.body.question,
      answer: typeof req.body.answer,
      sort_order: typeof req.body.sort_order,
      is_active: typeof req.body.is_active
    });
    
    const { site_id, category_id, product_id, question, answer, sort_order, is_active } = req.body;
    
    if (!site_id || !question || !answer) {
      console.log('Validation failed:', { site_id, question: !!question, answer: !!answer });
      return res.status(400).json({ 
        success: false, 
        message: 'site_id, question ve answer alanları gerekli' 
      });
    }

    // Convert string values to proper types
    const processedData = [
      parseInt(site_id), 
      category_id ? parseInt(category_id) : null, 
      product_id ? parseInt(product_id) : null, 
      question, 
      answer, 
      parseInt(sort_order) || 0, 
      is_active !== false
    ];
    
    console.log('Processed data for SQL:', processedData);

    const connection = getConnection();
    const [result] = await connection.execute(
      `INSERT INTO product_faqs (site_id, category_id, product_id, question, answer, sort_order, is_active) 
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      processedData
    );

    res.status(201).json({ 
      success: true, 
      message: 'FAQ başarıyla oluşturuldu',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('Product FAQ oluşturma hatası:', error);
    console.log(error)
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

app.post('/api/admin/customer-reviews', authMiddleware ,async (req, res) => {
  try {
    const { site_id, category_id, product_id, customer_name, customer_profession, review_text, rating, sort_order, is_active } = req.body;
    
    if (!site_id || !customer_name || !review_text) {
      return res.status(400).json({ 
        success: false, 
        message: 'site_id, customer_name ve review_text alanları gerekli' 
      });
    }

    const processedData = [
      parseInt(site_id), 
      category_id ? parseInt(category_id) : null, 
      product_id ? parseInt(product_id) : null, 
      customer_name, 
      customer_profession || null,
      review_text,
      rating ? parseInt(rating) : 5,
      parseInt(sort_order) || 0, 
      is_active !== false
    ];

    const connection = getConnection();
    const [result] = await connection.execute(
      `INSERT INTO customer_reviews (site_id, category_id, product_id, customer_name, customer_profession, review_text, rating, sort_order, is_active) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      processedData
    );

    res.status(201).json({ 
      success: true, 
      message: 'Customer Review başarıyla oluşturuldu',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('Customer Review oluşturma hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

app.put('/api/admin/product-faqs/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params;
    const { site_id, category_id, product_id, question, answer, sort_order, is_active } = req.body;
    
    if (!question || !answer) {
      return res.status(400).json({ 
        success: false, 
        message: 'question ve answer alanları gerekli' 
      });
    }

    const connection = getConnection();
    const [result] = await connection.execute(
      `UPDATE product_faqs 
       SET site_id = ?, category_id = ?, product_id = ?, question = ?, answer = ?, 
           sort_order = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
       WHERE id = ?`,
      [site_id, category_id || null, product_id || null, question, answer, sort_order || 0, is_active !== false, id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ 
        success: false, 
        message: 'FAQ bulunamadı' 
      });
    }

    res.json({ 
      success: true, 
      message: 'FAQ başarıyla güncellendi' 
    });
  } catch (error) {
    console.error('Product FAQ güncelleme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

app.put('/api/admin/customer-reviews/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params;
    const { site_id, category_id, product_id, customer_name, customer_profession, review_text, rating, sort_order, is_active } = req.body;
    
    if (!customer_name || !review_text) {
      return res.status(400).json({ 
        success: false, 
        message: 'customer_name ve review_text alanları gerekli' 
      });
    }

    const connection = getConnection();
    const [result] = await connection.execute(
      `UPDATE customer_reviews 
       SET site_id = ?, category_id = ?, product_id = ?, customer_name = ?, customer_profession = ?, 
           review_text = ?, rating = ?, sort_order = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
       WHERE id = ?`,
      [site_id, category_id || null, product_id || null, customer_name, customer_profession || null, 
       review_text, rating ? parseInt(rating) : 5, sort_order || 0, is_active !== false, id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ 
        success: false, 
        message: 'Customer Review bulunamadı' 
      });
    }

    res.json({ 
      success: true, 
      message: 'Customer Review başarıyla güncellendi' 
    });
  } catch (error) {
    console.error('Customer Review güncelleme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

app.delete('/api/admin/product-faqs/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params;

    const connection = getConnection();
    const [result] = await connection.execute(
      'DELETE FROM product_faqs WHERE id = ?',
      [id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ 
        success: false, 
        message: 'FAQ bulunamadı' 
      });
    }

    res.json({ 
      success: true, 
      message: 'FAQ başarıyla silindi' 
    });
  } catch (error) {
    console.error('Product FAQ silme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

app.delete('/api/admin/customer-reviews/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params;

    const connection = getConnection();
    const [result] = await connection.execute(
      'DELETE FROM customer_reviews WHERE id = ?',
      [id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ 
        success: false, 
        message: 'Customer Review bulunamadı' 
      });
    }

    res.json({ 
      success: true, 
      message: 'Customer Review başarıyla silindi' 
    });
  } catch (error) {
    console.error('Customer Review silme hatası:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Sunucu hatası' 
    });
  }
});

// 404 handler - moved to the end
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: 'Endpoint bulunamadı'
  });
});

// Error handler
app.use((error, req, res, next) => {
  console.error('Global error:', error);
  res.status(500).json({
    success: false,
    message: `Sunucu hatası:${error}`,
    error: process.env.NODE_ENV === 'development' ? error.message : undefined
  });
});

const startServer = async () => {
  try {
    await connectDB();
    
    app.listen(PORT, () => {
      console.log(`
        Port: ${PORT}
        API: http://localhost:${PORT}/api
        Health: http://localhost:${PORT}/api/health
      `);
    });
  } catch (error) {
    console.error('Server başlatılamadı:', error);
    process.exit(1);
  }
};

startServer();