import { NextResponse } from "next/server"
import { desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties } from "@/lib/db/schema"
import { propertySchema } from "@/lib/validations"
import { resolveApiRequest } from "@/lib/api-auth"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
import { geocodeAddress } from "@/lib/geocoding"

// Public REST API (v1) — Bearer API-key auth. All data is scoped by the
// resolved account owner id (team-aware), never the raw session user.

const unauthorized = () =>
  NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
const forbidden = () =>
  NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })

export async function GET(request: Request) {
  const ctx = await resolveApiRequest(request)
  if (!ctx) return unauthorized()

  const data = await db.query.properties.findMany({
    where: eq(properties.user_id, ctx.ownerId),
    with: { units: { columns: { id: true, status: true } } },
    orderBy: desc(properties.created_at),
  })

  return NextResponse.json({ data, count: data.length })
}

export async function POST(request: Request) {
  const ctx = await resolveApiRequest(request)
  if (!ctx) return unauthorized()
  if (!ctx.canWrite) return forbidden()

  const body = await request.json().catch(() => null)
  const parsed = propertySchema.safeParse(body)
  if (!parsed.success) {
    return NextResponse.json(
      { error: { code: 400, message: parsed.error.flatten() } },
      { status: 400 }
    )
  }

  const coords = await geocodeAddress(parsed.data)

  const [data] = await db
    .insert(properties)
    .values({ ...parsed.data, user_id: ctx.ownerId, ...(coords ?? {}) })
    .returning()

  await emitWebhookEvent({ ownerId: ctx.ownerId, event: "property.created", data: { property: data } })

  return NextResponse.json({ data }, { status: 201 })
}
