<?php
// api/news_download_ticket.php
// Authenticated endpoint that returns a short-lived signed download URL.

declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/news_common.php';

try {
    rvu_ensure_news_tables($pdo);
    $user = rvu_news_require_user($pdo);
    if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        rvu_news_json(['detail' => 'Method not allowed.'], 405);
    }

    $input = rvu_news_input();
    $newsId = (int)($input['news_id'] ?? 0);
    $type = strtolower(trim((string)($input['type'] ?? '')));
    if ($newsId <= 0 || !in_array($type, ['images', 'video'], true)) {
        rvu_news_json(['detail' => 'Valid news_id and type are required.'], 422);
    }

    $article = rvu_news_fetch_article($pdo, $newsId, (int)$user['id']);
    if (!$article) rvu_news_json(['detail' => 'News article not found.'], 404);
    if ($article['status'] === 'draft' && !rvu_news_can_manage($user, (int)$article['author_id'])) {
        rvu_news_json(['detail' => 'You cannot download media from this draft.'], 403);
    }

    if ($type === 'images' && empty($article['images'])) {
        rvu_news_json(['detail' => 'This story has no pictures to download.'], 404);
    }
    if ($type === 'video' && empty($article['video'])) {
        rvu_news_json(['detail' => 'This story has no video to download.'], 404);
    }

    $expires = time() + 300; // 5 minutes
    $signature = rvu_news_download_signature($newsId, $type, $expires);
    $url = rvu_news_base_url() . '/api/news_download.php?news_id=' . $newsId
         . '&type=' . rawurlencode($type)
         . '&expires=' . $expires
         . '&signature=' . rawurlencode($signature);

    rvu_news_json([
        'url' => $url,
        'expires_at' => gmdate(DATE_ATOM, $expires),
    ]);
} catch (Throwable $e) {
    rvu_news_json(['detail' => 'Unable to prepare media download: ' . $e->getMessage()], 500);
}
