import tar from 'tar';
import { NextResponse } from 'next/server';
import { statSync, createReadStream, existsSync } from 'fs';
import path from 'path';
import { gzip } from 'zlib';


// This is the route for exporting posts when using the local production server
// If you try this on the docker server, it will fail because the posts directory is not on the docker server

export async function GET() {
  try {
    const localDir = 'posts';
    const tarballName = 'local-export.tar.gz';
    const tarballPath = path.join('/tmp', tarballName);

    if (!existsSync(localDir)) {
      return NextResponse.json({ error: `${localDir} directory does not exist` }, { status: 400 });
    }
    
    await tar.c(
        {
        gzip: true,
        file: tarballPath,
        cwd: path.dirname(localDir),
        portable: true,
        noMtime: true,
      },
      [path.basename(localDir)]
    );

    const stat = statSync(tarballPath);
    const stream = createReadStream(tarballPath);

    return new Response(stream as any, {
      status: 200,
      headers: {
        'Content-Type': 'application/gzip',
        'Content-Disposition': `attachment; filename="${tarballName}"`,
        'Content-Length': stat.size.toString(),
      },
    });
  } catch (error) {
    console.error('Error exporting local:', error);
    return NextResponse.json({ error: 'Error exporting local' }, { status: 500 });
  }
}
