import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { minioClient } from '@/lib/minio';
import { env } from '@/lib/env';

const createFolderSchema = z.object({
  path: z.string().min(1).max(500),
});

export const POST = withAuth(
  withPermission('files', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createFolderSchema);

      // Sanitize path — no null bytes, no path traversal
      const safePath = body.path
        .replace(/\x00/g, '')
        .replace(/\.\.\//g, '')
        .replace(/^\/+/, '')
        .replace(/\/+/g, '/');

      if (!safePath) {
        throw new ValidationError('Invalid folder path');
      }

      const folderKey = `${ctx.portSlug}/${safePath}${safePath.endsWith('/') ? '' : '/'}`;

      // Create zero-byte marker object in MinIO
      await minioClient.putObject(env.MINIO_BUCKET, folderKey, Buffer.alloc(0), 0, {
        'Content-Type': 'application/x-directory',
      });

      return NextResponse.json({ data: { path: folderKey } }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
