import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

const BLOCKED_PREFIXES = ['/etc', '/sys', '/proc', '/System', '/Library/System', '/usr', '/bin', '/sbin', '/private/etc', '/private/sys', '/private/var/db', '/dev'];

function expandHome(p) {
  if (!p) return p;
  if (p === '~') return os.homedir();
  if (p.startsWith('~/')) return path.join(os.homedir() || '', p.slice(2));
  return p;
}

function isBlocked(abs) {
  return BLOCKED_PREFIXES.some((p) => abs === p || abs.startsWith(p + path.sep));
}

export async function POST(request) {
  let body;
  try { body = await request.json(); }
  catch { return Response.json({ error: 'invalid json' }, { status: 400 }); }

  const parentRaw = String(body.parent || '').trim();
  const nameRaw = String(body.name || '').trim();

  if (!parentRaw) return Response.json({ error: 'parent is required' }, { status: 400 });
  if (!nameRaw) return Response.json({ error: 'name is required' }, { status: 400 });
  if (nameRaw.length > 96) return Response.json({ error: 'name too long' }, { status: 400 });
  if (!/^[A-Za-z0-9._ -]+$/.test(nameRaw)) {
    return Response.json({ error: 'name may only contain letters, digits, dot, dash, underscore, space' }, { status: 400 });
  }
  if (nameRaw === '.' || nameRaw === '..' || nameRaw.startsWith('.')) {
    return Response.json({ error: 'name must not start with a dot' }, { status: 400 });
  }

  const parentExpanded = expandHome(parentRaw);
  if (!path.isAbsolute(parentExpanded)) {
    return Response.json({ error: 'parent must be an absolute path' }, { status: 400 });
  }
  const parentAbs = path.normalize(parentExpanded);
  if (isBlocked(parentAbs)) {
    return Response.json({ error: `parent path is inside a protected system directory` }, { status: 400 });
  }

  if (!fs.existsSync(parentAbs)) {
    return Response.json({ error: 'parent folder does not exist' }, { status: 400 });
  }
  const parentStat = fs.statSync(parentAbs);
  if (!parentStat.isDirectory()) {
    return Response.json({ error: 'parent path is not a folder' }, { status: 400 });
  }

  const target = path.join(parentAbs, nameRaw);
  if (!target.startsWith(parentAbs + path.sep)) {
    return Response.json({ error: 'resolved target escapes parent' }, { status: 400 });
  }

  try {
    fs.mkdirSync(target, { recursive: true });
    return Response.json({ folder_path: target, created: true });
  } catch (err) {
    return Response.json({ error: String(err?.message || err) }, { status: 500 });
  }
}
