var express = require("express");
var router = express.Router();
var path = require("path");
const fetch = require("node-fetch");
const fs = require("fs");
const airportData = JSON.parse(
  fs.readFileSync(path.join(__dirname, "../airportdata.json"), "utf8")
);
const db = require("../models");
const { create } = require("xmlbuilder2");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.sendFile(path.join(__dirname, "../views/index.html"));
});

// Weather API route
router.get("/api/weather", async function (req, res) {
  try {
    // Replace with your actual API key and city
    const apiKey = process.env.WEATHER_API_KEY;
    const city = "Toronto";
    const url = `http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${city}&aqi=no`;
    const response = await fetch(url);
    if (!response.ok) throw new Error("Weather API error");
    const data = await response.json();
    const temp_c = data.current.temp_c;
    const text = data.current.condition.text.toLowerCase();
    let condition = "sunny";
    if (text.includes("rain")) condition = "rain";
    else if (text.includes("snow")) condition = "snow";
    res.json({ temp_c, condition });
  } catch (err) {
    res.status(500).json({ error: "Failed to fetch weather" });
    console.error(err);
  }
});

// UTC time API route
router.get("/api/utc", function (req, res) {
  res.json({ utc: new Date().toISOString() });
});

// Autocomplete airports
router.get("/airports", function (req, res) {
  const search = (req.query.search || "").trim();
  if (search.length < 3) {
    return res
      .status(400)
      .json({ error: "Search term must be at least 3 characters" });
  }
  const term = search.toLowerCase();
  const matches = airportData
    .filter(
      (a) =>
        (a.name && a.name.toLowerCase().includes(term)) ||
        (a.code && a.code.toLowerCase().includes(term))
    )
    .slice(0, 10);
  res.json(matches);
});

// Log analytic event
router.post("/analytic", async function (req, res) {
  try {
    const { widget_name, browser_type } = req.body;
    if (!widget_name || !browser_type) {
      return res
        .status(400)
        .json({ error: "widget_name and browser_type required" });
    }
    await db.analytic.create({ widget_name, browser_type });
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: "Failed to log analytic" });
  }
});

// Count analytic rows
router.get("/analytic/count", async function (req, res) {
  try {
    const count = await db.analytic.count();
    res.json({ count });
  } catch (err) {
    res.status(500).json({ error: "Failed to count analytics" });
  }
});

// Export analytic as XML
router.get("/analytic/export", async function (req, res) {
  try {
    const analytics = await db.analytic.findAll({ raw: true });
    const root = create({ version: "1.0" }).ele("analytics");
    analytics.forEach((a) => {
      root
        .ele("analytic")
        .ele("id")
        .txt(a.id)
        .up()
        .ele("create_at")
        .txt(a.create_at)
        .up()
        .ele("widget_name")
        .txt(a.widget_name)
        .up()
        .ele("browser_type")
        .txt(a.browser_type)
        .up()
        .up();
    });
    const xml = root.end({ prettyPrint: true });
    res.set("Content-Type", "application/xml");
    res.set("Content-Disposition", 'attachment; filename="analytics.xml"');
    res.send(xml);
  } catch (err) {
    res.status(500).json({ error: "Failed to export analytics" });
  }
});

// Reddit widget route
router.get("/reddit", async function (req, res) {
  try {
    const response = await fetch("https://www.reddit.com/r/programming.json");
    if (!response.ok) throw new Error("Reddit API error");
    const data = await response.json();
    const posts = (data.data.children || [])
      .map((c) => c.data)
      .filter((_, i) => i % 2 === 0)
      .slice(0, 4)
      .map((post) => ({
        title: post.title,
        url: "https://reddit.com" + post.permalink,
        author: post.author,
      }));
    res.json(posts);
  } catch (err) {
    res.status(500).json({ error: "Failed to fetch reddit posts" });
  }
});

// Coin calculator route
router.post("/coin-calc", function (req, res) {
  try {
    let { amount } = req.body;
    amount = parseFloat(amount);
    if (isNaN(amount) || amount < 0)
      return res.status(400).json({ error: "Invalid amount" });
    const denoms = [20, 10, 5, 1, 0.25, 0.1, 0.05, 0.01];
    const result = [];
    let remaining = Math.round(amount * 100); // work in cents
    for (let d of denoms) {
      let denomCents = Math.round(d * 100);
      let count = Math.floor(remaining / denomCents);
      if (count > 0) {
        result.push({ denomination: d, count });
        remaining -= count * denomCents;
      }
    }
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: "Failed to calculate coins" });
  }
});

module.exports = router;
