import { NextResponse } from "next/server"
import { createAiChatCompletion, getAiErrorMessage, parseAiChatPayload } from "@/shared/lib/ai"
import { rateLimit, rateLimitKey, rateLimitHeaders, RATE_LIMIT_RULES } from "@/shared/lib/rate-limit"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"

export const dynamic = "force-dynamic"

const getStatusFromError = (message: string): number => {
  if (message === "Invalid payload" || message === "Messages are required") return 400
  if (message === "AI API key missing") return 500
  if (message === "Empty response") return 502
  return 502
}

export async function POST(req: Request): Promise<NextResponse> {
  try {
    const ctx = await requirePermission(Permissions.AI_CHAT)
    const userId = ctx.userId

    // Rate limit AI chat per user
    const limitKey = rateLimitKey("ai-chat", userId)
    const limit = rateLimit({ key: limitKey, ...RATE_LIMIT_RULES.AI_CHAT })
    if (!limit.success) {
      return NextResponse.json(
        { success: false, message: "Rate limit exceeded. Please slow down." },
        { status: 429, headers: rateLimitHeaders(limit) }
      )
    }

    const body = await req.json().catch(() => null)
    const input = parseAiChatPayload(body)
    const result = await createAiChatCompletion(input)
    return NextResponse.json(
      { success: true, content: result.content, usage: result.usage },
      { headers: rateLimitHeaders(limit) }
    )
  } catch (e) {
    if (e instanceof PermissionDeniedError) {
      return NextResponse.json(
        { success: false, message: e.message },
        { status: 403 }
      )
    }
    const message = getAiErrorMessage(e)
    return NextResponse.json({ success: false, message }, { status: getStatusFromError(message) })
  }
}
