const express = require('express');
const router = express.Router();
const Platform = require('../models/Platform');
const Category = require('../models/Category');
const authMiddleware = require('../middleware/auth');

router.get('/', async (req, res) => {
  try {
    const platforms = await Platform.findAll();
    res.json({
      success: true,
      data: platforms
    });
  } catch (error) {
    console.error('Platforms fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Platformlar getirilemedi'
    });
  }
});

router.get('/:slug', async (req, res) => {
  try {
    const platform = await Platform.findBySlug(req.params.slug);
    
    if (!platform) {
      return res.status(404).json({
        success: false,
        message: 'Platform bulunamadı'
      });
    }

    const categories = await Category.findByPlatform(platform.id);
    
    res.json({
      success: true,
      data: {
        ...platform,
        categories
      }
    });
  } catch (error) {
    console.error('Platform fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Platform getirilemedi'
    });
  }
});

// Admin routes
router.post('/', authMiddleware, async (req, res) => {
  try {
    const platform = await Platform.create(req.body);
    res.status(201).json({
      success: true,
      data: platform,
      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ı'
    });
  }
});

router.put('/:id', authMiddleware, async (req, res) => {
  try {
    const platform = await Platform.update(req.params.id, req.body);
    
    if (!platform) {
      return res.status(404).json({
        success: false,
        message: 'Platform bulunamadı'
      });
    }

    res.json({
      success: true,
      data: platform,
      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'
    });
  }
});

router.delete('/:id', authMiddleware, async (req, res) => {
  try {
    await Platform.delete(req.params.id);
    res.json({
      success: true,
      message: 'Platform başarıyla silindi'
    });
  } catch (error) {
    console.error('Platform delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Platform silinemedi'
    });
  }
});

module.exports = router;