import { db } from "@/app/db/db";
import { bulkAddressUploads } from "@/app/db/schema/bulk_address_uploads";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const BodySchema = z.object({
  fileKey: z.string(),
  filename: z.string(),
  portfolioId: z.string(),
  userId: z.string(),
  sourceHeaders: z
    .array(z.union([z.string(), z.null(), z.undefined()]))
    .default([])
    .transform((arr) =>
      arr.filter((h): h is string => typeof h === "string" && h.trim().length > 0)
    ),
});

export async function POST(request: NextRequest) {
  let body;
  try {
    body = BodySchema.parse(await request.json());
  } catch (error) {
    console.error("Invalid input:", error);
    return NextResponse.json({ error: "Invalid input" }, { status: 400 });
  }

  const bucket = process.env.RETROFIT_PLAN_INPUT_BUCKET_NAME;
  if (!bucket) {
    console.error("RETROFIT_PLAN_INPUT_BUCKET_NAME not set");
    return NextResponse.json({ error: "Server misconfiguration" }, { status: 500 });
  }

  try {
    const [record] = await db
      .insert(bulkAddressUploads)
      .values({
        portfolioId: body.portfolioId,
        userId: body.userId,
        s3Bucket: bucket,
        s3Key: body.fileKey,
        filename: body.filename,
        sourceHeaders: body.sourceHeaders,
      })
      .returning();

    return NextResponse.json(
      { id: record.id, s3Key: record.s3Key, s3Bucket: record.s3Bucket, status: record.status },
      { status: 201 }
    );
  } catch (error) {
    console.error("Failed to record upload:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
