import { NextRequest, NextResponse } from "next/server";
import { requireApiAuth } from "@/lib/api-auth";

// 禁止向内网地址发起请求，防止 SSRF 攻击
const PRIVATE_HOST_PATTERNS = [
    /^localhost$/i,
    /^127\.\d+\.\d+\.\d+$/,
    /^10\.\d+\.\d+\.\d+$/,
    /^172\.(1[6-9]|2\d|3[01])\.\d+\.\d+$/,
    /^192\.168\.\d+\.\d+$/,
    /^0\.0\.0\.0$/,
    /^\[::1?\]$/,
    /^169\.254\.\d+\.\d+$/, // Link-local
];

function isPrivateHost(hostname: string): boolean {
    return PRIVATE_HOST_PATTERNS.some((pattern) => pattern.test(hostname));
}

export async function POST(req: NextRequest) {
    const authError = await requireApiAuth();
    if (authError) return authError;

    try {
        const { messages, config } = await req.json();
        const { apiKey, baseURL, model } = config || {};

        if (!apiKey || typeof apiKey !== "string") {
            return NextResponse.json({ error: "Missing API Key" }, { status: 400 });
        }
        if (!baseURL || typeof baseURL !== "string") {
            return NextResponse.json({ error: "Missing API base URL" }, { status: 400 });
        }
        if (!Array.isArray(messages)) {
            return NextResponse.json({ error: "Invalid messages payload" }, { status: 400 });
        }
        if (messages.length === 0 || messages.length > 100) {
            return NextResponse.json({ error: "Messages count out of range" }, { status: 400 });
        }
        const isValidMessage = messages.every(
            (msg) =>
                msg &&
                typeof msg === "object" &&
                typeof msg.role === "string" &&
                typeof msg.content === "string" &&
                msg.content.length <= 20000
        );
        if (!isValidMessage) {
            return NextResponse.json({ error: "Invalid message format" }, { status: 400 });
        }

        let normalizedBaseUrl: string;
        try {
            const parsed = new URL(baseURL);
            if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
                return NextResponse.json({ error: "Unsupported API base URL protocol" }, { status: 400 });
            }
            // SSRF 防护：禁止向内网地址发起请求
            if (isPrivateHost(parsed.hostname)) {
                return NextResponse.json({ error: "API base URL must not point to a private/internal address" }, { status: 400 });
            }
            normalizedBaseUrl = parsed.origin + parsed.pathname.replace(/\/$/, "");
        } catch {
            return NextResponse.json({ error: "Invalid API base URL" }, { status: 400 });
        }

        const url = `${normalizedBaseUrl}/chat/completions`;

        const res = await fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${apiKey}`,
            },
            body: JSON.stringify({
                model: typeof model === "string" && model.trim() ? model.trim() : "gpt-3.5-turbo",
                messages,
                stream: true, // 强制使用流式
            }),
        });

        if (!res.ok) {
            const errorText = await res.text();
            return NextResponse.json({ error: `Upstream Error: ${res.statusText}`, details: errorText }, { status: res.status });
        }

        // 直接返回上游 stream
        return new Response(res.body, {
            headers: {
                "Content-Type": "text/event-stream",
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
            },
        });

    } catch (error) {
        console.error("AI API Error:", error);
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}

