import { NextResponse } from "next/server"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { ai_recommendations } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getAccountContext } from "@/lib/account"
import { logActivity } from "@/lib/activity"

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const ctx = await getAccountContext(user.id)
  if (!ctx.canWrite) return NextResponse.json({ error: "Forbidden" }, { status: 403 })
  const ownerId = ctx.ownerId

  const { id } = await params
  const { status } = await request.json() as { status: "approved" | "dismissed" }

  if (!["approved", "dismissed"].includes(status)) {
    return NextResponse.json({ error: "Invalid status" }, { status: 400 })
  }

  const updateData: Record<string, unknown> = { status }
  if (status === "approved") updateData.applied_at = new Date().toISOString()
  if (status === "dismissed") updateData.dismissed_at = new Date().toISOString()

  const [data] = await db
    .update(ai_recommendations)
    .set(updateData)
    .where(and(eq(ai_recommendations.id, id), eq(ai_recommendations.user_id, ownerId)))
    .returning()

  if (!data) return NextResponse.json({ error: "Not found" }, { status: 404 })

  await logActivity({
    userId: ownerId,
    type: "ai_action",
    title: status === "approved"
      ? `AI recommendation approved: ${data.title}`
      : `AI recommendation dismissed: ${data.title}`,
    entityType: "ai_recommendation",
    entityId: id,
  })

  return NextResponse.json(data)
}
