import Fastify from "fastify";
import helmet from "@fastify/helmet";
import rateLimit from "@fastify/rate-limit";
import cors from "@fastify/cors";
import fastifyStatic from "@fastify/static";
import path from "path";
import { fileURLToPath } from "url";

import { checkIp } from "./checkIp.js";

const fastify = Fastify();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
await fastify.register(fastifyStatic, {
  root: path.join(__dirname, "./web/landing/dist"),
});
await fastify.register(helmet, {
  contentSecurityPolicy: false,
  noSniff: false,
});

await fastify.register(rateLimit, {
  max: (request) => (request.headers["x-api-key"] ? 100 : 1),
  timeWindow: "1 second",
  keyGenerator: (request) => request.headers["x-api-key"] || request.ip,
  addHeaders: {
    "x-ratelimit-limit": true,
    "x-ratelimit-remaining": true,
    "x-ratelimit-reset": true,
  },
});

await fastify.register(cors);

fastify.get(
  "/api/ip/:ip",
  {
    schema: {
      params: {
        type: "object",
        properties: {
          ip: { type: "string", format: "ipv4" },
        },
        required: ["ip"],
      },
    },
  },
  async function handler(request, reply) {
    try {
      const datacenter = checkIp(request.params.ip);
      reply.header("Content-Type", "application/json");
      reply.send({ datacenter });
    } catch (err) {
      reply.code(500).send({ error: "Internal Server Error" });
    }
  }
);

try {
  await fastify.listen({ port: 3000 });
} catch (err) {
  fastify.log.error(err);
  process.exit(1);
}
