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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { path: itemPath, name, type, recursive } = body;
    
    if (!name || !type) {
      return NextResponse.json(
        { error: 'Missing required parameters' },
        { status: 400 }
      );
    }

    // Construct the full path to the item
    const basePath = process.cwd();
    const postsDir = getPostsDirectory();
    
    // Ensure the posts directory exists
    try {
      await fs.access(postsDir);
    } catch {
      return NextResponse.json({ error: 'Posts directory not found' }, { status: 404 });
    }

    // Construct the full path to the item
    let fullPath: string;
    if (type === 'post') {
      fullPath = path.join(postsDir, itemPath || '', `${name}.md`);
    } else {
      fullPath = path.join(postsDir, itemPath || '', name);
    }

    console.log('Attempting to delete:', {
      basePath,
      postsDir,
      fullPath,
      itemPath,
      name,
      type
    });

    // Check if the item exists
    try {
      await fs.access(fullPath);
    } catch (error) {
      console.error('Item not found:', fullPath);
      return NextResponse.json({ 
        error: 'Item not found',
        details: {
          path: fullPath,
          itemPath,
          name,
          type
        }
      }, { status: 404 });
    }

    // For folders, check if it's empty unless recursive is true
    if (type === 'folder' && !recursive) {
      try {
        const files = await fs.readdir(fullPath);
        if (files.length > 0) {
          return NextResponse.json(
            { error: 'Cannot delete non-empty folder' },
            { status: 400 }
          );
        }
      } catch (error) {
        console.error('Error checking folder contents:', error);
        return NextResponse.json(
          { error: 'Error checking folder contents' },
          { status: 500 }
        );
      }
    }

    // Delete the item
    try {
      await fs.rm(fullPath, { recursive: true, force: true });
      return NextResponse.json({ 
        success: true,
        deleted: {
          path: fullPath,
          itemPath,
          name,
          type
        }
      });
    } catch (error) {
      console.error('Error deleting item:', error);
      return NextResponse.json(
        { error: 'Error deleting item' },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error('Error processing delete request:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
} 