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

// Public routes
router.get('/', async (req, res) => {
  try {
    const categories = await Category.findAll();
    res.json({
      success: true,
      data: categories
    });
  } catch (error) {
    console.error('Categories fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Kategoriler getirilemedi'
    });
  }
});

router.get('/by-slug/:platformSlug/:categorySlug', async (req, res) => {
  try {
    const { platformSlug, categorySlug } = req.params;
    const category = await Category.findBySlug(platformSlug, categorySlug);
    
    if (!category) {
      return res.status(404).json({
        success: false,
        message: 'Kategori bulunamadı'
      });
    }

    const products = await Product.findByCategory(category.id);
    
    res.json({
      success: true,
      data: {
        ...category,
        products
      }
    });
  } catch (error) {
    console.error('Category fetch error:', error);
    res.status(500).json({
      success: false,
      message: 'Kategori getirilemedi'
    });
  }
});

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

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

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

router.delete('/:id', authMiddleware, async (req, res) => {
  try {
    await Category.delete(req.params.id);
    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'
    });
  }
});

module.exports = router;