/**
 * adminServiceRoutes.js - Service Management API Endpoints
 * Purpose: CRUD operations for services and service management
 * Routes: 6 endpoints for service management
 */

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

// GET /api/admin/services - List all services with pagination & filtering
router.get('/services', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;
    const search = req.query.search || '';
    const categoryId = req.query.category_id || null;
    const status = req.query.status || null;
    const providerId = req.query.provider_id || null;

    // Build WHERE clause
    let whereConditions = [];
    let params = [];

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

    if (categoryId) {
      whereConditions.push(`s.category_id = ?`);
      params.push(categoryId);
    }

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

    if (providerId) {
      whereConditions.push(`s.api_provider_id = ?`);
      params.push(providerId);
    }

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

    // Get total count
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM services s ${whereClause}`,
      params
    );
    const total = countResult[0].total;

    // Get paginated services
    const [services] = await pool.execute(
      `SELECT
        s.id, s.name, s.description, s.price as rate, s.status, s.created_at,
        c.name as category, p.name as provider
      FROM services s
      LEFT JOIN categories c ON s.category_id = c.id
      LEFT JOIN api_providers p ON s.api_provider_id = p.id
      ${whereClause}
      ORDER BY s.created_at DESC
      LIMIT ? OFFSET ?`,
      [...params, limit, offset]
    );

    res.json({
      success: true,
      message: 'Services retrieved successfully',
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      },
      data: services
    });
  } catch (error) {
    console.error('Service list error:', error);
    res.status(500).json({
      success: false,
      error: 'Service Error',
      message: error.message
    });
  }
});

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

    const [services] = await pool.execute(
      `SELECT
        s.id, s.name, s.description, s.price as rate, s.status, s.created_at, s.updated_at,
        c.id as category_id, c.name as category,
        p.id as provider_id, p.name as provider,
        COUNT(DISTINCT o.id) as order_count,
        SUM(o.quantity) as total_quantity
      FROM services s
      LEFT JOIN categories c ON s.category_id = c.id
      LEFT JOIN api_providers p ON s.api_provider_id = p.id
      LEFT JOIN orders o ON s.id = o.service_id
      WHERE s.id = ?
      GROUP BY s.id`,
      [id]
    );

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

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

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

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

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

    // Update service
    await pool.execute(
      `UPDATE services SET name = ?, description = ?, price = ?, status = ?, category_id = ?, updated_at = NOW()
       WHERE id = ?`,
      [name, description, rate, status, category_id, id]
    );

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

// POST /api/admin/services - Create new service
router.post('/services', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { name, description, rate, status, category_id, provider_id } = req.body;

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

    const [result] = await pool.execute(
      `INSERT INTO services (name, description, price, status, category_id, api_provider_id, created_at)
       VALUES (?, ?, ?, ?, ?, ?, NOW())`,
      [name, description || '', rate, status || 'active', category_id || null, provider_id || null]
    );

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

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

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

    // Delete service
    await pool.execute('DELETE FROM services WHERE id = ?', [id]);

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

// PUT /api/admin/services/:id/status - Toggle service status
router.put('/services/:id/status', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;
    const { status } = req.body;

    if (!status || !['active', 'inactive'].includes(status)) {
      return res.status(400).json({
        success: false,
        error: 'Validation Error',
        message: 'status must be either "active" or "inactive"'
      });
    }

    const [result] = await pool.execute(
      'UPDATE services SET status = ?, updated_at = NOW() WHERE id = ?',
      [status, id]
    );

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

    res.json({
      success: true,
      message: `Service status changed to ${status}`,
      data: { id, status }
    });
  } catch (error) {
    console.error('Status update error:', error);
    res.status(500).json({
      success: false,
      error: 'Update Error',
      message: error.message
    });
  }
});

module.exports = router;
