import { NextResponse } from "next/server"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { maintenance_requests, notifications, profiles } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { maintenanceSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
import { getEffectiveOwnerId, getAccountContext } from "@/lib/account"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
import { z } from "zod"

const maintenancePatchSchema = maintenanceSchema.partial().extend({
  status: z.enum(["open", "in_progress", "resolved", "closed"]).optional(),
  resolution_notes: z.string().optional(),
  actual_cost: z.number().positive().optional(),
  resolved_at: z.string().optional(),
})

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

  const ownerId = await getEffectiveOwnerId(user.id)

  const { id } = await params
  const data = await db.query.maintenance_requests.findFirst({
    where: and(eq(maintenance_requests.id, id), eq(maintenance_requests.user_id, ownerId)),
    with: {
      property: { columns: { name: true, address_line1: true, city: true } },
      unit: { columns: { unit_number: true } },
      tenant: { columns: { first_name: true, last_name: true, email: true, phone: true } },
    },
  })

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

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)
  const ownerId = ctx.ownerId
  if (!ctx.canWrite) return NextResponse.json({ error: "Forbidden" }, { status: 403 })

  const { id } = await params
  const body = await request.json()
  const parsed = maintenancePatchSchema.safeParse(body)
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })

  if (
    !(await ownsProperty(ownerId, parsed.data.property_id)) ||
    !(await ownsUnit(ownerId, parsed.data.unit_id)) ||
    !(await ownsTenant(ownerId, parsed.data.tenant_id))
  ) {
    return NextResponse.json({ error: "Invalid reference" }, { status: 403 })
  }

  // Read the current row so we can tell whether the status actually changed.
  const existing = await db.query.maintenance_requests.findFirst({
    where: and(eq(maintenance_requests.id, id), eq(maintenance_requests.user_id, ownerId)),
    columns: { status: true, title: true },
  })

  const updateData: Record<string, unknown> = { ...parsed.data }

  // Auto-set resolved_at when status → resolved
  if (parsed.data.status === "resolved" && !parsed.data.resolved_at) {
    updateData.resolved_at = new Date().toISOString()
  }

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

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

  // If the status actually changed, drop a dashboard notification row for the
  // owner and fire the maintenance.updated webhook.
  if (parsed.data.status && existing && parsed.data.status !== existing.status) {
    const owner = await db.query.profiles.findFirst({
      where: eq(profiles.id, ownerId),
      columns: { email: true },
    })
    if (owner?.email) {
      await db.insert(notifications).values({
        user_id: ownerId,
        type: "maintenance_update",
        recipient_email: owner.email,
        subject: `Maintenance "${data.title}" marked ${data.status}`,
        status: "sent",
        metadata: {
          maintenance_id: id,
          status: data.status,
          body: `Status changed from ${existing.status} to ${data.status}.`,
        },
      })
    }

    await emitWebhookEvent({
      ownerId,
      event: "maintenance.updated",
      data: { maintenance: data, previous_status: existing.status },
    })
  }

  return NextResponse.json(data)
}

export async function DELETE(_: 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)
  const ownerId = ctx.ownerId
  if (!ctx.canWrite) return NextResponse.json({ error: "Forbidden" }, { status: 403 })

  const { id } = await params
  await db
    .delete(maintenance_requests)
    .where(and(eq(maintenance_requests.id, id), eq(maintenance_requests.user_id, ownerId)))

  return NextResponse.json({ success: true })
}
