// app/db/surveyDB/api/insert_data_to_uploaded_files/route.ts
import { NextResponse } from "next/server";
import { z, ZodError } from "zod";
import { insertUploadedFile } from "../../utils/utility"; // ensure path is correct
import { ReportTypeSchema, reportTypeToDbLabel } from "../../schema/documents";
export const runtime = "nodejs";

// Helper: "" or whitespace -> undefined (so optional() can drop it)
const emptyToUndefined = (v: unknown) => {
  if (typeof v === "string" && v.trim() === "") return undefined;
  return v;
};

const BodySchema = z.object({
  s3JsonUri: z.preprocess(
    emptyToUndefined,
    z.string().url().optional()
  ),
  s3FileUri: z.string().url(),
  docType: ReportTypeSchema,
  // Required upload timestamp (coerce from ISO string)
  s3FileUploadTimestamp: z.coerce.date(),
  // Optional JSON timestamp: allow "" -> undefined, then coerce to Date
  s3JsonUploadTimestamp: z.preprocess(
    emptyToUndefined,
    z.coerce.date().optional()
  ),
  uprn: z.string().min(1),
});

export async function POST(req: Request) {
  try {
    const parsed = BodySchema.parse(await req.json());

    const row = await insertUploadedFile({
      s3JsonUri: parsed.s3JsonUri, // undefined -> util converts to null
      s3FileUri: parsed.s3FileUri,
      docType: parsed.docType,
      s3FileUploadTimestamp: parsed.s3FileUploadTimestamp,
      s3JsonUploadTimestamp: parsed.s3JsonUploadTimestamp, // undefined -> util converts to null
      uprn: parsed.uprn,
    });

    return NextResponse.json(row, { status: 201 });
  } catch (e) {
    if (e instanceof ZodError) {
      return NextResponse.json(
        { error: "Invalid payload", details: e.flatten() },
        { status: 400 }
      );
    }
    console.error(e);
    return NextResponse.json(
      { error: "Failed to insert uploaded_file table in surveyDB" },
      { status: 500 }
    );
  }
}
