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

const postsDirectory = getPostsDirectory();

export async function POST(request: Request) {
  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    const folderPath = formData.get('path') as string;

    if (!file) {
      return NextResponse.json(
        { error: 'No file provided' },
        { status: 400 }
      );
    }

    // Read the file content
    const content = await file.text();
    
    // Parse frontmatter
    const { data, content: markdownContent } = matter(content);

    // Create slug from filename (without .md extension)
    const slug = file.name.replace(/\.md$/, '');

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

    // Ensure the directory exists
    fs.mkdirSync(path.dirname(fullPath), { recursive: true });

    // Write the file
    fs.writeFileSync(fullPath, content);

    return NextResponse.json({ 
      success: true, 
      path: fullPath,
      slug,
      title: data.title || slug,
      date: data.date || new Date().toISOString().split('T')[0],
      tags: data.tags || [],
      summary: data.summary || '',
      author: process.env.NEXT_PUBLIC_BLOG_OWNER + "'s" || 'Anonymous',
    });
  } catch (error) {
    console.error('Error uploading file:', error);
    return NextResponse.json(
      { error: 'Error uploading file' },
      { status: 500 }
    );
  }
} 