import type { FastifyReply, FastifyRequest } from "fastify";
import { eq } from "drizzle-orm";
import { pushInstances } from "@fedeo/push-db";
import { env } from "../config/env.js";
import { db } from "../db/client.js";
import { decryptSecret, hmacSha256, secureEqual, sha256 } from "./crypto.js";

export async function requireAdmin(request: FastifyRequest, reply: FastifyReply): Promise<void> {
  const token = request.headers.authorization?.replace(/^Bearer\s+/i, "") || String(request.headers["x-admin-token"] || "");
  if (!token || !secureEqual(token, env.ADMIN_TOKEN)) {
    await reply.code(401).send({ error: "admin_unauthorized", message: "Admin-Token fehlt oder ist ungültig." });
  }
}

export async function requireInstance(request: FastifyRequest, reply: FastifyReply): Promise<void> {
  const instanceId = String(request.headers["x-fedeo-instance-id"] || "");
  const timestamp = String(request.headers["x-fedeo-timestamp"] || "");
  const signature = String(request.headers["x-fedeo-signature"] || "");

  if (!instanceId || !timestamp || !signature) {
    await reply.code(401).send({ error: "instance_auth_missing", message: "Instanzsignatur fehlt." });
    return;
  }

  const timestampMs = Date.parse(timestamp);
  if (!Number.isFinite(timestampMs) || Math.abs(Date.now() - timestampMs) > 5 * 60 * 1000) {
    await reply.code(401).send({ error: "instance_timestamp_invalid", message: "Instanzsignatur ist abgelaufen oder ungültig." });
    return;
  }

  const [instance] = await db.select().from(pushInstances).where(eq(pushInstances.instanceId, instanceId)).limit(1);
  if (!instance || instance.status !== "active") {
    await reply.code(403).send({ error: "instance_not_allowed", message: "Instanz ist nicht aktiv." });
    return;
  }

  const path = request.url.split("?")[0] || request.url;
  const bodyHash = sha256(request.rawBody || "");
  const canonical = [request.method.toUpperCase(), path, timestamp, bodyHash, instanceId].join("\n");
  const secrets = [instance.currentSecretEncrypted, instance.nextSecretEncrypted].filter(Boolean) as string[];
  const accepted = secrets.some((encrypted) => {
    const expected = hmacSha256(decryptSecret(encrypted), canonical);
    return secureEqual(signature, expected);
  });

  if (!accepted) {
    await reply.code(401).send({ error: "instance_signature_invalid", message: "Instanzsignatur ist ungültig." });
    return;
  }

  request.pushInstance = instance;
}
