import { auth } from "@/auth";
import { generateUploadUrl, buildStorageKey } from "@/lib/storage";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const signSchema = z.object({
  fileName: z.string().min(1),
  mimeType: z.string().min(1),
  poId: z.string().min(1),
  type: z.enum(["po-document", "receipt"]),
});

export async function POST(request: NextRequest) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const parsed = signSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid request" }, { status: 400 });
  }

  const { fileName, mimeType, poId, type } = parsed.data;
  const key = buildStorageKey(type, poId, fileName);

  try {
    const uploadUrl = await generateUploadUrl(key, mimeType);
    return NextResponse.json({ uploadUrl, key });
  } catch {
    return NextResponse.json({ error: "Failed to generate upload URL" }, { status: 500 });
  }
}
