import { NextRequest, NextResponse } from "next/server"
import { and, eq, ilike, or } from "drizzle-orm"
import { db } from "@/lib/db"
import { tenants, properties, maintenance_requests } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"

export async function GET(req: NextRequest) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const ownerId = await getEffectiveOwnerId(user.id)

  const q = req.nextUrl.searchParams.get("q")?.trim() ?? ""
  if (q.length < 2) return NextResponse.json({ tenants: [], properties: [], maintenance: [] })

  const like = `%${q}%`

  const [tenantRows, propertyRows, maintenanceRows] = await Promise.all([
    db
      .select({
        id: tenants.id,
        first_name: tenants.first_name,
        last_name: tenants.last_name,
        email: tenants.email,
        status: tenants.status,
      })
      .from(tenants)
      .where(
        and(
          eq(tenants.user_id, ownerId),
          or(ilike(tenants.first_name, like), ilike(tenants.last_name, like), ilike(tenants.email, like))
        )
      )
      .limit(5),
    db
      .select({
        id: properties.id,
        name: properties.name,
        address_line1: properties.address_line1,
        city: properties.city,
      })
      .from(properties)
      .where(
        and(
          eq(properties.user_id, ownerId),
          or(ilike(properties.name, like), ilike(properties.address_line1, like), ilike(properties.city, like))
        )
      )
      .limit(5),
    db
      .select({
        id: maintenance_requests.id,
        title: maintenance_requests.title,
        status: maintenance_requests.status,
        priority: maintenance_requests.priority,
      })
      .from(maintenance_requests)
      .where(and(eq(maintenance_requests.user_id, ownerId), ilike(maintenance_requests.title, like)))
      .limit(5),
  ])

  return NextResponse.json({
    tenants: tenantRows,
    properties: propertyRows,
    maintenance: maintenanceRows,
  })
}
