<?php

/**
 * Multi-Product Firmware API - List Endpoint
 *
 * URL Format: /api/v1/{product}/{stage}/{device}/list
 * Example: /api/v1/climate-controller/prod/rm-e32-r6-b6/list
 *
 * Query Parameters:
 * - limit: Maximum number of versions to return (default: 10)
 * - build_type: Filter by build type (dev, prod)
 *
 * Response Format:
 * {
 *   "product": "climate-controller",
 *   "device": "rm-e32-r6-b6",
 *   "stage": "prod",
 *   "total_count": 15,
 *   "returned_count": 10,
 *   "firmware_list": [
 *     {
 *       "version": "v1.2.3",
 *       "build_type": "prod",
 *       "filename": "climate-controller-rm-e32-r6-b6-v1.2.3-prod.bin",
 *       "size": 1252464,
 *       "modified": 1757075710,
 *       "download_url": "https://firmware.ryzer.one/products/climate-controller/prod/rm-e32-r6-b6/...",
 *       "metadata": {...}
 *     }
 *   ]
 * }
 */

require_once 'common.php';

// Parse URL path from REQUEST_URI
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
$pathInfo = parse_url($requestUri, PHP_URL_PATH);

// Extract path after /api/v1/ - handle both PATH_INFO and REQUEST_URI parsing
if (strpos($pathInfo, '/api/v1/') === 0) {
    $apiPath = substr($pathInfo, 8); // Remove '/api/v1/' prefix
    $pathParts = array_filter(explode('/', $apiPath));
} else {
    $pathInfo = $_SERVER['PATH_INFO'] ?? '';
    $pathParts = array_filter(explode('/', $pathInfo));
}

if (count($pathParts) < 4) {
    sendError('Invalid URL format. Expected: /api/v1/{product}/{stage}/{device}/list', 400);
}

$product = $pathParts[0];
$stage = $pathParts[1];
$device = $pathParts[2];
$endpoint = $pathParts[3];

if ($endpoint !== 'list') {
    sendError('Unknown endpoint. Expected: list', 404);
}

// Validate parameters
$error = validateParameters($product, $stage, $device);
if ($error) {
    sendError($error['error'], 400);
}

// Get query parameters
$limit = min(50, max(1, intval($_GET['limit'] ?? 10))); // Limit between 1-50
$buildTypeFilter = $_GET['build_type'] ?? null;

// Log the access
logAccess($product, $stage, $device, 'list_firmware');

// Get all firmware files
$allFirmware = getFirmwareFiles($product, $stage, $device);

// Filter by build type if requested
if ($buildTypeFilter) {
    $allFirmware = array_filter($allFirmware, function ($firmware) use ($buildTypeFilter) {
        return ($firmware['build_type'] ?? 'unknown') === $buildTypeFilter;
    });
    $allFirmware = array_values($allFirmware); // Re-index array
}

$totalCount = count($allFirmware);
$firmwareList = array_slice($allFirmware, 0, $limit);

// Format the firmware list
$formattedList = [];
foreach ($firmwareList as $firmware) {
    $item = [
        'version' => $firmware['version'] ?? 'unknown',
        'build_type' => $firmware['build_type'] ?? 'unknown',
        'filename' => $firmware['bin_file'],
        'size' => $firmware['size'],
        'modified' => $firmware['modified'],
        'modified_iso' => date('c', $firmware['modified']),
        'download_url' => getDownloadUrl($product, $stage, $device, $firmware['bin_file'])
    ];

    // Add metadata if available
    if (isset($firmware['metadata'])) {
        $item['metadata'] = $firmware['metadata'];
    }

    $formattedList[] = $item;
}

$response = [
    'product' => $product,
    'device' => $device,
    'stage' => $stage,
    'total_count' => $totalCount,
    'returned_count' => count($formattedList),
    'limit_applied' => $limit,
    'firmware_list' => $formattedList
];

// Add filter info if applied
if ($buildTypeFilter) {
    $response['filter'] = ['build_type' => $buildTypeFilter];
}

sendJsonResponse($response);
