import fastify from "fastify";
import Database from "better-sqlite3";
import fetch from "node-fetch";
import { v4 as uuid } from "uuid";

const db = new Database("weathery.db");
const APPID = "d6f0f985f37372e9824c68a52662cc23";

const app = fastify({
  logger: true,
});

app.post("/locations", async (req) => {
  const payload: any = req.body;
  const location = {
    id: uuid(),
    name: payload.name,
  };

  db.prepare("INSERT INTO locations (id, name) VALUES (@id, @name)").run(
    location
  );

  return location;
});

app.get("/locations", async () => {
  const locations = db.prepare("SELECT * FROM locations").all();

  return { locations };
});

app.get("/", async () => {
  const locations = db.prepare("SELECT * FROM locations").all();

  const weathers = await Promise.all(
    locations.map(async (location) => {
      const { lat, lon } = location;
      const { weather, main: properties } = await fetch(
        `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${APPID}&units=metric`
      ).then((r) => r.json());

      return {
        ...location,
        weather,
        properties,
      };
    })
  );

  return weathers;
});

app.listen(8080);
