import { NextResponse } from "next/server";
import { randomBytes } from "node:crypto";
import { db } from "@/db";
import { messengerLoginRequests } from "@/db/schema";
import { isSettingEnabled } from "@/lib/auth";
import { getBotInfo } from "@/lib/bot-api";
import { checkRateLimit, readJson } from "@/lib/api-security";
import { ApiRequestError } from "@/lib/api-security";

const MESSENGERS = ["telegram", "max"] as const;
const NONCE_TTL_MS = 5 * 60 * 1000;

/** Issues a one-time nonce and a bot deep link (contract §2в). */
export async function POST(request: Request) {
  try {
    if (!(await isSettingEnabled("auth_enabled"))) return NextResponse.json({ error: "auth_disabled" }, { status: 403 });
    if (!db) return NextResponse.json({ error: "service_unavailable" }, { status: 503 });
    checkRateLimit(request, "msg-login-start", 10, 10 * 60 * 1000);
    const body = await readJson<{ messenger?: unknown }>(request, 2 * 1024);
    const messenger = MESSENGERS.find((candidate) => candidate === body.messenger);
    if (!messenger) return NextResponse.json({ error: "bad_request" }, { status: 400 });
    if (!(await isSettingEnabled(messenger === "telegram" ? "auth_telegram_enabled" : "auth_max_enabled"))) {
      return NextResponse.json({ error: "provider_disabled" }, { status: 403 });
    }

    let botLink: string | null = null;
    if (messenger === "telegram") {
      try { botLink = process.env.MESSENGER_TELEGRAM_URL || (await getBotInfo()).tg_link; } catch { botLink = process.env.MESSENGER_TELEGRAM_URL || null; }
    } else {
      botLink = process.env.MESSENGER_MAX_URL || null;
    }
    const nonce = randomBytes(16).toString("base64url");
    const loginUrl = botLink ? new URL(botLink) : null;
    loginUrl?.searchParams.set("start", `login-${nonce}`);
    await db.insert(messengerLoginRequests).values({ nonce, messenger, expiresAt: new Date(Date.now() + NONCE_TTL_MS) });
    return NextResponse.json({
      nonce,
      url: loginUrl?.toString() || null,
      command: `/start login-${nonce}`,
      expiresIn: Math.floor(NONCE_TTL_MS / 1000)
    }, { headers: { "Cache-Control": "no-store" } });
  } catch (error) {
    if (error instanceof ApiRequestError) return NextResponse.json({ error: "too_many_requests" }, { status: error.status });
    return NextResponse.json({ error: "service_unavailable" }, { status: 503 });
  }
}
