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 { getStorageBackend } from '@/lib/storage';

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

export const POST = withAuth(
  withPermission('files', 'manage_folders', 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('/') ? '' : '/'}`;

      // Zero-byte marker through the active storage backend. S3 stores it
      // as an empty object; the filesystem backend currently materializes
      // it as an empty file (a future refactor should move folder
      // bookkeeping to a DB-backed virtual-folder table - see
      // docs/audit-comprehensive-2026-05-05.md HIGH §3 follow-up).
      await (
        await getStorageBackend()
      ).put(folderKey, Buffer.alloc(0), {
        contentType: 'application/x-directory',
        sizeBytes: 0,
      });

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