import { db } from "@/app/db/db";
import { property } from "@/app/db/schema/property";
import { serializeBigInt } from "@/app/utils";
import { eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest, props: { params: Promise<{ propertyId: string }> }) {
  const params = await props.params;
  const propertyId = params.propertyId;

  const propertyMeta = await db.query.property.findFirst({
    columns: {
      id: true,
      uprn: true,
      address: true,
      postcode: true,
      hasPreConditionReport: true,
      hasRecommendations: true,
      createdAt: true,
      propertyType: true,
      builtForm: true,
      localAuthority: true,
      constituency: true,
      numberOfRooms: true,
      yearBuilt: true,
      tenure: true,
      currentEpcRating: true,
      currentSapPoints: true,
      originalSapPoints: true,
      updatedAt: true,
      currentValuation: true,
    },
    where: eq(property.id, BigInt(propertyId)),
    with: {
      detailsEpc: {
        columns: {
          currentEnergyDemand: true,
          co2Emissions: true,
          estimated: true,
        },
      },
    },
  });

  if (!propertyMeta) {
    return new NextResponse(null, { status: 404 });
  }

  return new NextResponse(JSON.stringify(propertyMeta, serializeBigInt));
}
