import { d as defineEventHandler, b as getRouterParam, c as createError, v as exists, w as readMultipartFormData, u as useRuntimeConfig } from '../../../../nitro/nitro.mjs';
import { mkdir, writeFile } from 'fs/promises';
import { join } from 'path';
import { c as create } from '../../../../_/attachments.service.mjs';
import 'node:http';
import 'node:https';
import 'node:crypto';
import 'stream';
import 'events';
import 'http';
import 'crypto';
import 'buffer';
import 'zlib';
import 'https';
import 'net';
import 'tls';
import 'url';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'vue-router';
import '@prisma/client';
import '@prisma/adapter-better-sqlite3';
import 'fs';
import 'child_process';
import 'node:child_process';
import 'node:url';

function getAutocodeRoot() {
  const config = useRuntimeConfig();
  return config["autocodeRoot"] || join(process.cwd(), "autocode");
}
const attachments_post = defineEventHandler(async (event) => {
  const id = getRouterParam(event, "id");
  if (!id) {
    throw createError({
      statusCode: 400,
      message: "Issue ID required"
    });
  }
  const issueExists = await exists(id);
  if (!issueExists) {
    throw createError({
      statusCode: 404,
      message: `Issue not found: ${id}`
    });
  }
  try {
    const formData = await readMultipartFormData(event);
    if (!formData || formData.length === 0) {
      throw createError({
        statusCode: 400,
        message: "No file uploaded"
      });
    }
    const file = formData[0];
    if (!file || !file.filename || !file.data) {
      throw createError({
        statusCode: 400,
        message: "Invalid file data"
      });
    }
    const autocodeRoot = getAutocodeRoot();
    const attachmentsDir = join(autocodeRoot, "attachments", id);
    await mkdir(attachmentsDir, { recursive: true });
    const timestamp = Date.now();
    const safeFilename = `${timestamp}_${file.filename.replace(/[^a-zA-Z0-9._-]/g, "_")}`;
    const filepath = join(attachmentsDir, safeFilename);
    await writeFile(filepath, file.data);
    const attachment = await create(id, {
      filename: file.filename,
      filepath: `attachments/${id}/${safeFilename}`,
      mimetype: file.type || "application/octet-stream",
      size: file.data.length
    });
    return {
      id: attachment.id,
      filename: attachment.filename,
      mimetype: attachment.mimetype,
      size: attachment.size,
      createdAt: attachment.createdAt.toISOString()
    };
  } catch (err) {
    if (err && typeof err === "object" && "statusCode" in err) {
      throw err;
    }
    throw createError({
      statusCode: 500,
      message: err instanceof Error ? err.message : "Upload failed"
    });
  }
});

export { attachments_post as default };
//# sourceMappingURL=attachments.post.mjs.map
