import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { db } from "@/app/db/db";
import { property } from "@/app/db/schema/property";
import { and, asc, count, eq, isNotNull } from "drizzle-orm";

// GET — distinct postcodes (with counts) for the Run-filter options. One
// grouped, portfolio-scoped query (ix_property_portfolio).
export async function GET(
  _request: NextRequest,
  props: { params: Promise<{ portfolioId: string }> },
) {
  const session = await getServerSession(AuthOptions);
  if (!session?.user?.email) {
    return NextResponse.json({ error: "Unauthorised" }, { status: 401 });
  }
  const { portfolioId } = await props.params;
  if (!/^\d+$/.test(portfolioId)) {
    return NextResponse.json({ error: "Invalid portfolio id" }, { status: 400 });
  }
  try {
    const rows = await db
      .select({ postcode: property.postcode, n: count() })
      .from(property)
      .where(
        and(
          eq(property.portfolioId, BigInt(portfolioId)),
          eq(property.markedForDeletion, false),
          isNotNull(property.postcode),
        ),
      )
      .groupBy(property.postcode)
      .orderBy(asc(property.postcode));
    return NextResponse.json({
      postcodes: rows.map((r) => ({ postcode: r.postcode, count: r.n })),
    });
  } catch (err) {
    console.error("GET /postcodes error:", err);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
