import { NextResponse } from "next/server"
import { and, desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { notifications, rent_payments, maintenance_requests } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { sendEmail, rentDueReminderHtml, maintenanceUpdateHtml } from "@/lib/email/send"
import { formatCurrency, formatDate } from "@/lib/utils"
import { getEffectiveOwnerId, getAccountContext } from "@/lib/account"

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

  const ownerId = await getEffectiveOwnerId(user.id)

  try {
    const data = await db
      .select()
      .from(notifications)
      .where(eq(notifications.user_id, ownerId))
      .orderBy(desc(notifications.sent_at))
      .limit(50)

    return NextResponse.json(data)
  } catch (e) {
    return NextResponse.json({ error: (e as Error).message }, { status: 500 })
  }
}

export async function POST(request: Request) {
  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 body = await request.json() as {
    type: string
    payment_id?: string
    maintenance_id?: string
  }

  let result

  if (body.type === "rent_reminder" && body.payment_id) {
    const payment = await db.query.rent_payments.findFirst({
      where: and(eq(rent_payments.id, body.payment_id), eq(rent_payments.user_id, ownerId)),
      with: {
        tenant: { columns: { first_name: true, last_name: true, email: true } },
        property: { columns: { name: true } },
        unit: { columns: { unit_number: true } },
      },
    })

    if (!payment?.tenant?.email) {
      return NextResponse.json({ error: "Tenant has no email" }, { status: 400 })
    }

    result = await sendEmail({
      to: payment.tenant.email,
      subject: `Rent Due Reminder — ${payment.property.name}`,
      html: rentDueReminderHtml({
        tenantName: `${payment.tenant.first_name} ${payment.tenant.last_name}`,
        propertyName: payment.property.name,
        unitNumber: payment.unit?.unit_number ?? "—",
        amount: formatCurrency(payment.amount),
        dueDate: formatDate(payment.due_date),
      }),
    })

    if (result.success) {
      await db.insert(notifications).values({
        user_id: ownerId,
        type: "rent_reminder",
        recipient_email: payment.tenant.email,
        subject: `Rent Due Reminder — ${payment.property.name}`,
        status: "sent",
        metadata: {
          payment_id: body.payment_id,
          body: `Reminder sent to ${payment.tenant.first_name} ${payment.tenant.last_name} for ${formatCurrency(payment.amount)} due ${formatDate(payment.due_date)}.`,
        },
      })
    }
  }

  if (body.type === "maintenance_update" && body.maintenance_id) {
    const req = await db.query.maintenance_requests.findFirst({
      where: and(eq(maintenance_requests.id, body.maintenance_id), eq(maintenance_requests.user_id, ownerId)),
      with: {
        tenant: { columns: { first_name: true, last_name: true, email: true } },
      },
    })

    if (!req?.tenant?.email) {
      return NextResponse.json({ error: "Tenant has no email" }, { status: 400 })
    }

    result = await sendEmail({
      to: req.tenant.email,
      subject: `Maintenance Update — ${req.title}`,
      html: maintenanceUpdateHtml({
        tenantName: `${req.tenant.first_name} ${req.tenant.last_name}`,
        title: req.title,
        status: req.status,
        resolutionNotes: req.resolution_notes ?? undefined,
      }),
    })
  }

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