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);

    // Deduplicate rows that arise when the ingestion Lambda re-triggers for a deal
    // that was already processed: same S3 key gets a new version, but a new DB row
    // is written each time.
    //
    // Step 1: same s3FileKey → keep the row with the most recent upload timestamp.
    const latestByS3Key = new Map<string, (typeof rows)[number]>();
    for (const row of rows) {
      const existing = latestByS3Key.get(row.s3FileKey);
      if (!existing || row.s3UploadTimestamp > existing.s3UploadTimestamp) {
        latestByS3Key.set(row.s3FileKey, row);
      }
    }

    // Step 2: among distinct keys, same (fileType, measureName) → keep latest.
    // Rows with null fileType (unclassified) are kept as-is.
    const latestByDocType = new Map<string, (typeof rows)[number]>();
    const unclassified: (typeof rows)[number][] = [];
    for (const row of latestByS3Key.values()) {
      if (!row.fileType) { unclassified.push(row); continue; }
      const key = `${row.fileType}:${row.measureName ?? ""}`;
      const existing = latestByDocType.get(key);
      if (!existing || row.s3UploadTimestamp > existing.s3UploadTimestamp) {
        latestByDocType.set(key, row);
      }
    }

    const dedupedRows = [...latestByDocType.values(), ...unclassified];

    const documents = dedupedRows.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 },
    );
  }
}
