/**
 * adminCategoryRoutes.js - Category Management API Endpoints
 * Purpose: CRUD operations for service categories
 * Routes: 5 endpoints for category management
 */

const express = require('express');
const router = express.Router();

// GET /api/admin/categories - List all categories
router.get('/categories', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const search = req.query.search || '';
    const status = req.query.status || null;

    let whereConditions = [];
    let params = [];

    if (search) {
      whereConditions.push(`name LIKE ?`);
      params.push(`%${search}%`);
    }

    if (status) {
      whereConditions.push(`status = ?`);
      params.push(status);
    }

    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';

    // Get categories with service count
    const [categories] = await pool.execute(
      `SELECT
        c.id, c.name, c.description, c.icon_class as icon, c.status, c.created_at, c.updated_at,
        COUNT(s.id) as service_count
      FROM categories c
      LEFT JOIN services s ON c.id = s.category_id
      ${whereClause}
      GROUP BY c.id, c.name, c.description, c.icon_class, c.status, c.created_at, c.updated_at
      ORDER BY c.name ASC`,
      params
    );

    res.json({
      success: true,
      message: 'Categories retrieved successfully',
      data: categories
    });
  } catch (error) {
    console.error('Category list error:', error);
    res.status(500).json({
      success: false,
      error: 'Category Error',
      message: error.message
    });
  }
});

// GET /api/admin/categories/:id - Get category details
router.get('/categories/:id', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;

    const [categories] = await pool.execute(
      `SELECT
        c.id, c.name, c.description, c.icon_class as icon, c.status, c.created_at, c.updated_at,
        COUNT(s.id) as service_count,
        SUM(CASE WHEN o.id IS NOT NULL THEN 1 ELSE 0 END) as order_count
      FROM categories c
      LEFT JOIN services s ON c.id = s.category_id
      LEFT JOIN orders o ON s.id = o.service_id
      WHERE c.id = ?
      GROUP BY c.id, c.name, c.description, c.icon_class, c.status, c.created_at, c.updated_at`,
      [id]
    );

    if (categories.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Not Found',
        message: 'Category not found'
      });
    }

    // Get services in this category
    const [services] = await pool.execute(
      'SELECT id, name, price as rate, status FROM services WHERE category_id = ? ORDER BY name',
      [id]
    );

    res.json({
      success: true,
      message: 'Category retrieved successfully',
      data: {
        ...categories[0],
        services: services
      }
    });
  } catch (error) {
    console.error('Category fetch error:', error);
    res.status(500).json({
      success: false,
      error: 'Category Error',
      message: error.message
    });
  }
});

// POST /api/admin/categories - Create new category
router.post('/categories', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { name, description, icon, status } = req.body;

    // Validate input
    if (!name) {
      return res.status(400).json({
        success: false,
        error: 'Validation Error',
        message: 'name is required'
      });
    }

    // Check if category already exists
    const [existing] = await pool.execute('SELECT id FROM categories WHERE name = ?', [name]);
    if (existing.length > 0) {
      return res.status(400).json({
        success: false,
        error: 'Conflict',
        message: 'Category with this name already exists'
      });
    }

    const [result] = await pool.execute(
      `INSERT INTO categories (name, description, icon_class, status, created_at)
       VALUES (?, ?, ?, ?, NOW())`,
      [name, description || '', icon || 'fas fa-th', status || 'active']
    );

    res.status(201).json({
      success: true,
      message: 'Category created successfully',
      data: {
        id: result.insertId,
        name,
        status: status || 'active'
      }
    });
  } catch (error) {
    console.error('Category create error:', error);
    res.status(500).json({
      success: false,
      error: 'Create Error',
      message: error.message
    });
  }
});

// PUT /api/admin/categories/:id - Update category
router.put('/categories/:id', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;
    const { name, description, icon, status } = req.body;

    // Verify category exists
    const [existing] = await pool.execute('SELECT id FROM categories WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Not Found',
        message: 'Category not found'
      });
    }

    // Update category
    const updates = [];
    const updateValues = [];
    if (name !== undefined) { updates.push('name = ?'); updateValues.push(name); }
    if (description !== undefined) { updates.push('description = ?'); updateValues.push(description); }
    if (icon !== undefined) { updates.push('icon_class = ?'); updateValues.push(icon); }
    if (status !== undefined) { updates.push('status = ?'); updateValues.push(status); }

    if (updates.length > 0) {
      updates.push('updated_at = NOW()');
      updateValues.push(id);
      await pool.execute(
        `UPDATE categories SET ${updates.join(', ')} WHERE id = ?`,
        updateValues
      );
    }

    res.json({
      success: true,
      message: 'Category updated successfully',
      data: { id, name }
    });
  } catch (error) {
    console.error('Category update error:', error);
    res.status(500).json({
      success: false,
      error: 'Update Error',
      message: error.message
    });
  }
});

// DELETE /api/admin/categories/:id - Delete category
router.delete('/categories/:id', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;

    // Check if category has services
    const [services] = await pool.execute('SELECT id FROM services WHERE category_id = ?', [id]);
    if (services.length > 0) {
      return res.status(400).json({
        success: false,
        error: 'Conflict',
        message: `Cannot delete category with ${services.length} services. Remove services first.`
      });
    }

    // Delete category
    const [result] = await pool.execute('DELETE FROM categories WHERE id = ?', [id]);

    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        error: 'Not Found',
        message: 'Category not found'
      });
    }

    res.json({
      success: true,
      message: 'Category deleted successfully'
    });
  } catch (error) {
    console.error('Category delete error:', error);
    res.status(500).json({
      success: false,
      error: 'Delete Error',
      message: error.message
    });
  }
});

module.exports = router;
