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

const postsDirectory = getPostsDirectory();

export async function GET(
  request: Request,
  { params }: { params: { slug: string[] | string } }
) {
  try {
    const slugArr = Array.isArray(params.slug) ? params.slug : [params.slug];
    const slugPath = slugArr.join('/');
    const rustResult = spawnSync(
      path.resolve(process.cwd(), 'markdown_backend/target/release/markdown_backend'),
      ['show', slugPath],
      { encoding: 'utf-8' }
    );
    if (rustResult.status === 0 && rustResult.stdout) {
      const post = JSON.parse(rustResult.stdout);
      const fs = require('fs');
      const filePath = path.join(postsDirectory, slugPath + '.md');
      let raw = '';
      try {
        raw = fs.readFileSync(filePath, 'utf8');
      } catch {}
      post.raw = raw;
      post.createdAt = post.created_at;
      delete post.created_at;
      return NextResponse.json(post);
    } else {
      const rustError = rustResult.stderr || rustResult.error?.toString() || 'Unknown error';
      return NextResponse.json({ error: 'Rust parser error', details: rustError }, { status: 500 });
    }
  } catch (error) {
    return NextResponse.json(
      { error: 'Error loading post', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    );
  }
}

export async function POST(request: Request, { params }: { params: { slug: string[] | string } }) {
  try {
    const { markdown } = await request.json();
    if (typeof markdown !== 'string') {
      return NextResponse.json({ error: 'Invalid markdown' }, { status: 400 });
    }
    const slugArr = Array.isArray(params.slug) ? params.slug : [params.slug];
    const slugPath = slugArr.join('/');
    const filePath = path.join(postsDirectory, slugPath + '.md');
    require('fs').writeFileSync(filePath, markdown, 'utf8');
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Error saving file', details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 });
  }
}
 