import { NextResponse } from "next/server";
import { eq } from "drizzle-orm";
import { db } from "@/app/db/db";
import { uploadedFiles } from "@/app/db/schema/uploaded_files";

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const dealIdParam = searchParams.get("dealId");
  const uprnParam = searchParams.get("uprn");
  const landlordPropertyIdParam = searchParams.get("landlordPropertyId");

  if (!dealIdParam && !uprnParam && !landlordPropertyIdParam) {
    return NextResponse.json(
      { error: "dealId, uprn, or landlordPropertyId is required" },
      { status: 400 },
    );
  }

  try {
    // Prefer dealId — reliable even when UPRN is missing from the deal.
    // Fall back to UPRN, then landlordPropertyId.
    const condition = dealIdParam
      ? eq(uploadedFiles.hubsotDealId, dealIdParam)
      : uprnParam
        ? eq(uploadedFiles.uprn, BigInt(uprnParam))
        : eq(uploadedFiles.landlordPropertyId, landlordPropertyIdParam!);

    const rows = await db
      .select({
        id: uploadedFiles.id,
        s3FileKey: uploadedFiles.s3FileKey,
        s3FileBucket: uploadedFiles.s3FileBucket,
        s3UploadTimestamp: uploadedFiles.s3UploadTimestamp,
        fileType: uploadedFiles.fileType,
        source: uploadedFiles.source,
        uprn: uploadedFiles.uprn,
        landlordPropertyId: uploadedFiles.landlordPropertyId,
        measureName: uploadedFiles.measureName,
      })
      .from(uploadedFiles)
      .where(condition);

    const documents = rows.map((row) => ({
      id: String(row.id),
      s3FileKey: row.s3FileKey,
      s3FileBucket: row.s3FileBucket,
      docType: row.fileType ?? "unknown",
      source: row.source ?? null,
      s3UploadTimestamp: row.s3UploadTimestamp.toISOString(),
      uprn: row.uprn !== null ? String(row.uprn) : null,
      landlordPropertyId: row.landlordPropertyId,
      measureName: row.measureName ?? null,
    }));

    return NextResponse.json(documents);
  } catch (error) {
    console.error("Error fetching property documents:", error);
    return NextResponse.json(
      { error: "Failed to fetch documents" },
      { status: 500 },
    );
  }
}
