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

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

export async function GET() {
  try {
    const dockerDir = '/app/docker'; // update this to your actual path
    const tarballName = 'docker-export.tar.gz';
    const tarballPath = path.join('/tmp', tarballName);

    if (!existsSync(dockerDir)) {
      return NextResponse.json({ error: `${dockerDir} directory does not exist` }, { status: 400 });
    }

    await tar.c(
      {
        gzip: true,
        file: tarballPath,
        cwd: path.dirname(dockerDir),
        portable: true,
        noMtime: true,
      },
      [path.basename(dockerDir)]
    );

    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 docker:', error);
    return NextResponse.json({ error: 'Error exporting docker' }, { status: 500 });
  }
}