import express from 'express';
import axios from 'axios';
const router = express.Router();

const LoveTik = {
  async dapatkan(url) {
    const response = await axios.post(
      "https://lovetik.com/api/ajax/search",
      `query=${encodeURIComponent(url)}`,
      { headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" } }
    );
    const data = response.data;
    if (!data.images) data.images = [];

    const result = { video: [], audio: [], images: data.images, slideshow: null };
    for (const item of data.links) {
      if (!item.a) continue;
      const formatted = {
        format: item.t.replace(/<.*?>|♪/g, "").trim(),
        resolution: item.s || "Audio Only",
        link: item.a
      };
      if (item.ft == 1) result.video.push(formatted);
      else result.audio.push(formatted);
    }

    const linkWithC = data.links.find((m) => m.c);
    if (linkWithC) {
      try {
        const rendered = await axios.post(
          "https://lovetik.com/api/ajax/convert",
          `c_data=${encodeURIComponent(linkWithC.c)}`,
          { headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" } }
        );
        result.slideshow = rendered.data;
      } catch (err) {
        console.log("Gagal convert slideshow:", err.message);
      }
    }
    return result;
  }
};

/**
 * @swagger
 * /downloader/tiktok:
 *   get:
 *     tags: [Downloader]
 *     summary: Downloader TikTok
 *     parameters:
 *       - in: query
 *         name: url
 *         required: true
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Berhasil
 */
router.get('/', async (req, res) => {
  const { url } = req.query;
  if (!url) return res.status(400).json({ status: false, error: "url is required" });
  const result = await LoveTik.dapatkan(url);
  res.json({ status: true, result });
});

export default router;