import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
import { getPostsDirectory } from '@/lib/postsDirectory';

const postsDirectory = getPostsDirectory();

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, path: folderPath } = body;

    // Create the full path for the new folder
    const fullPath = path.join(postsDirectory, folderPath, name);

    // Check if folder already exists
    if (fs.existsSync(fullPath)) {
      return NextResponse.json(
        { error: 'Folder already exists' },
        { status: 400 }
      );
    }

    // Create the folder
    fs.mkdirSync(fullPath, { recursive: true });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error creating folder:', error);
    return NextResponse.json(
      { error: 'Error creating folder' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: Request) {
  try {
    const body = await request.json();
    const { name, path: folderPath } = body;

    // Create the full path for the folder to delete
    const fullPath = path.join(postsDirectory, folderPath, name);

    // Check if folder exists
    if (!fs.existsSync(fullPath)) {
      return NextResponse.json(
        { error: 'Folder does not exist' },
        { status: 404 }
      );
    }

    // Check if folder is empty
    const files = fs.readdirSync(fullPath);
    if (files.length > 0) {
      return NextResponse.json(
        { error: 'Cannot delete non-empty folder' },
        { status: 400 }
      );
    }

    // Delete the folder
    fs.rmdirSync(fullPath);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting folder:', error);
    return NextResponse.json(
      { error: 'Error deleting folder' },
      { status: 500 }
    );
  }
} 