const db = require('../models');
const { sendResponse, sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');
const routingExecutionService = require('../services/routingExecutionService');

/**
 * Get routing executions for a Production Order
 * GET /api/v1/production/routing-execution/production-order/:productionOrderId
 */
exports.getByProductionOrder = asyncHandler(async (req, res) => {
  const { productionOrderId } = req.params;

  if (!productionOrderId) {
    return sendError(res, 'Production Order ID is required', 400);
  }

  const executions = await routingExecutionService.getRoutingExecutionsForProductionOrder(productionOrderId);

  sendResponse(res, 200, true, 'Routing executions retrieved successfully', executions);
});

/**
 * Get routing executions for shop-floor screen (across production orders)
 * GET /api/v1/production/routing-execution/shop-floor
 *
 * Query params:
 * - workCenterId (optional)
 * - date (optional, YYYY-MM-DD) filters planned_start_date
 * - status (optional, comma-separated; default: PENDING,IN_PROGRESS)
 * - limit, offset (optional)
 * - plantId (optional; defaults to user plant if present in query context)
 */
exports.getShopFloorOperations = asyncHandler(async (req, res) => {
  const {
    workCenterId,
    date,
    status,
    limit = 200,
    offset = 0,
    companyId: queryCompanyId,
    plantId: queryPlantId
  } = req.query;

  const companyId = queryCompanyId || (req.user && !req.user.isSuperAdmin ? req.user.companyId : null);
  const plantId = queryPlantId || null;

  const statuses = status
    ? String(status)
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)
    : ['PENDING', 'IN_PROGRESS'];

  const operations = await routingExecutionService.getShopFloorOperations({
    companyId: companyId ? parseInt(companyId, 10) : null,
    plantId: plantId ? parseInt(plantId, 10) : null,
    workCenterId: workCenterId ? parseInt(workCenterId, 10) : null,
    date: date || null,
    statuses,
    limit: parseInt(limit, 10),
    offset: parseInt(offset, 10)
  });

  sendResponse(res, 200, true, 'Shop-floor operations retrieved successfully', operations);
});

/**
 * Start a routing operation
 * POST /api/v1/production/routing-execution/:id/start
 */
exports.startOperation = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const userId = req.user?.userId || null;

  if (!id) {
    return sendError(res, 'Execution ID is required', 400);
  }

  try {
    const execution = await routingExecutionService.startOperation(id, userId);
    sendResponse(res, 200, true, 'Operation started successfully', execution);
  } catch (error) {
    sendError(res, error.message, 400);
  }
});

/**
 * Complete a routing operation
 * POST /api/v1/production/routing-execution/:id/complete
 */
exports.completeOperation = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const data = req.body;
  const userId = req.user?.userId || null;

  if (!id) {
    return sendError(res, 'Execution ID is required', 400);
  }

  try {
    const execution = await routingExecutionService.completeOperation(id, data, userId);
    sendResponse(res, 200, true, 'Operation completed successfully', execution);
  } catch (error) {
    sendError(res, error.message, 400);
  }
});

/**
 * Get work center utilization
 * GET /api/v1/production/routing-execution/work-center/:workCenterId/utilization
 */
exports.getWorkCenterUtilization = asyncHandler(async (req, res) => {
  const { workCenterId } = req.params;
  const { startDate, endDate } = req.query;

  if (!workCenterId) {
    return sendError(res, 'Work Center ID is required', 400);
  }

  if (!startDate || !endDate) {
    return sendError(res, 'Start date and end date are required', 400);
  }

  try {
    const utilization = await routingExecutionService.getWorkCenterUtilization(
      workCenterId,
      new Date(startDate),
      new Date(endDate)
    );
    sendResponse(res, 200, true, 'Work center utilization retrieved successfully', utilization);
  } catch (error) {
    sendError(res, error.message, 400);
  }
});

/**
 * Update Production Order dates from routing
 * POST /api/v1/production/routing-execution/production-order/:productionOrderId/update-dates
 */
exports.updateProductionOrderDates = asyncHandler(async (req, res) => {
  const { productionOrderId } = req.params;

  if (!productionOrderId) {
    return sendError(res, 'Production Order ID is required', 400);
  }

  try {
    const productionOrder = await routingExecutionService.updateProductionOrderDatesFromRouting(productionOrderId);
    if (!productionOrder) {
      return sendError(res, 'No routing executions found for this Production Order', 404);
    }
    sendResponse(res, 200, true, 'Production Order dates updated successfully', productionOrder);
  } catch (error) {
    sendError(res, error.message, 400);
  }
});

