// ─── rentals.js ──────────────────────────────────────────────
const express = require('express');
const rentalsRouter = express.Router();
const { query } = require('../utils/db');
const { requireFirebaseAuth } = require('../middleware/auth');
const { getPresignedDownloadUrl } = require('../services/r2');

/**
 * POST /api/rentals
 * Initiate a rental after payment confirmation.
 * Body: { movieId, paymentReference }
 */
rentalsRouter.post('/', requireFirebaseAuth, async (req, res) => {
  try {
    const { movieId, paymentReference } = req.body;
    const { uid } = req.user;

    // Verify the payment exists and is completed
    const paymentCheck = await query(
      "SELECT id, amount, status FROM payments WHERE reference = $1 AND status = 'completed'",
      [paymentReference]
    );
    if (!paymentCheck.rows.length) {
      return res.status(400).json({ success: false, message: 'Payment not found or not completed' });
    }

    // Check no active rental already exists
    const existing = await query(
      "SELECT id FROM rentals WHERE user_firebase_uid=$1 AND movie_id=$2 AND status='active' AND expires_at>NOW()",
      [uid, movieId]
    );
    if (existing.rows.length) {
      return res.status(409).json({ success: false, message: 'Active rental already exists' });
    }

    const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours
    const result = await query(`
      INSERT INTO rentals (user_firebase_uid, movie_id, payment_reference, status, expires_at)
      VALUES ($1, $2, $3, 'active', $4)
      RETURNING *
    `, [uid, movieId, paymentReference, expiresAt]);

    res.status(201).json({ success: true, rental: result.rows[0] });
  } catch (err) {
    console.error('Create rental error:', err);
    res.status(500).json({ success: false, message: 'Failed to create rental' });
  }
});

/**
 * GET /api/rentals/my
 * List current user's rentals.
 */
rentalsRouter.get('/my', requireFirebaseAuth, async (req, res) => {
  try {
    const result = await query(`
      SELECT r.id, r.status, r.expires_at, r.created_at,
             m.id as movie_id, m.title, m.poster_url, m.duration, m.quality, m.size_mb
      FROM rentals r
      JOIN movies m ON m.id = r.movie_id
      WHERE r.user_firebase_uid = $1
      ORDER BY r.created_at DESC
    `, [req.user.uid]);

    res.json({ success: true, rentals: result.rows });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Failed to fetch rentals' });
  }
});

/**
 * GET /api/rentals/stream/:movieId
 * Returns a time-limited presigned URL to stream a rented movie.
 * Validates active rental before issuing the URL.
 */
rentalsRouter.get('/stream/:movieId', requireFirebaseAuth, async (req, res) => {
  try {
    const { movieId } = req.params;
    const { uid } = req.user;

    const rental = await query(
      "SELECT id FROM rentals WHERE user_firebase_uid=$1 AND movie_id=$2 AND status='active' AND expires_at>NOW()",
      [uid, movieId]
    );
    if (!rental.rows.length) {
      return res.status(403).json({ success: false, message: 'No active rental found for this movie' });
    }

    const movie = await query('SELECT video_r2_key, video_url FROM movies WHERE id=$1', [movieId]);
    if (!movie.rows.length || !movie.rows[0].video_r2_key) {
      return res.status(404).json({ success: false, message: 'Video not available' });
    }

    const streamUrl = await getPresignedDownloadUrl(movie.rows[0].video_r2_key, 14400); // 4 hours
    res.json({ success: true, streamUrl, expiresIn: 14400 });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Failed to generate stream URL' });
  }
});

module.exports = rentalsRouter;
