import { HttpError } from "@/server/http/errors";
import { ok } from "@/server/http/response";
import { withErrorHandling } from "@/server/http/withErrorHandling";
import { isSafeFilename } from "@/server/uploads/paths";
import { imageUploadService } from "@/server/uploads/service";

export const POST = withErrorHandling(async (request: Request) => {
  const formData = await request.formData();
  const file = formData.get("file");
  if (!file || !(file instanceof File)) {
    throw new HttpError("No file provided", { status: 400, code: "VALIDATION_ERROR" });
  }
  const result = await imageUploadService.uploadImage(file);
  return ok(result);
});

export const DELETE = withErrorHandling(async (request: Request) => {
  const { searchParams } = new URL(request.url);
  const filename = searchParams.get("filename");
  if (!filename) throw new HttpError("No filename provided", { status: 400, code: "VALIDATION_ERROR" });
  if (!isSafeFilename(filename))
    throw new HttpError("Invalid filename", { status: 400, code: "VALIDATION_ERROR" });
  await imageUploadService.deleteImage(filename);
  return ok({ success: true });
});
