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 { slug, from, to } = body;
    if (!slug) {
      return NextResponse.json({ error: 'Missing slug' }, { status: 400 });
    }
    // Compute source and destination paths
    const fromPath = from && from.trim() !== ''
      ? path.join(postsDirectory, from, `${slug}.md`)
      : path.join(postsDirectory, `${slug}.md`);
    const toPath = to && to.trim() !== ''
      ? path.join(postsDirectory, to, `${slug}.md`)
      : path.join(postsDirectory, `${slug}.md`);

    // Ensure source exists
    if (!fs.existsSync(fromPath)) {
      return NextResponse.json({ error: 'Source post does not exist' }, { status: 404 });
    }
    // Ensure destination directory exists
    fs.mkdirSync(path.dirname(toPath), { recursive: true });
    // Move the file
    fs.renameSync(fromPath, toPath);
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error moving post:', error);
    return NextResponse.json({ error: 'Error moving post' }, { status: 500 });
  }
} 