import express from 'express';
import pool from '../db/pool.js';

const router = express.Router();
// No session auth — called from AMPP Script Task inside broadcast network

/**
 * GET /api/v1/ampp/folder-for/:filename
 *
 * Returns the pre-created AMPP folder:id for a given asset filename.
 * Called by the simplified AMPP Script Task after ingest to link the asset
 * without having to parse filename prefixes or create folders itself.
 *
 * 200: { folder_id: "abc123" }
 * 404: { error: "..." }  (file not uploaded through Dragon-Wind — handle gracefully)
 */
router.get('/folder-for/:filename', async (req, res, next) => {
  try {
    const { filename } = req.params;
    const result = await pool.query(
      `SELECT ampp_folder_id FROM assets
       WHERE filename = $1 AND ampp_folder_id IS NOT NULL
       ORDER BY created_at DESC LIMIT 1`,
      [filename]
    );
    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'No AMPP folder mapping found for this filename' });
    }
    res.json({ folder_id: result.rows[0].ampp_folder_id });
  } catch (err) {
    next(err);
  }
});

export default router;
