/**
 * Video-Flow 导出视频下载API
 * 文件路径: video-flow/app/api/export/download/[exportId]/route.ts
 * 作者: 资深全栈开发工程师
 * 创建时间: 2025-01-08
 */

import { NextRequest, NextResponse } from "next/server";
import { tmpdir } from "os";
import { join } from "path";
import { promises as fs } from "fs";

export async function GET(
  request: NextRequest,
  { params }: { params: { exportId: string } }
) {
  try {
    const { exportId } = params;
    
    if (!exportId) {
      return NextResponse.json(
        { error: "导出ID不能为空" },
        { status: 400 }
      );
    }

    console.log('📥 Video-Flow 导出视频下载请求:', exportId);

    // 构建文件路径
    const workDir = join(tmpdir(), `video-flow-ai-export-${exportId}`);
    const filePath = join(workDir, 'output.mp4');

    // 检查文件是否存在
    try {
      await fs.access(filePath);
    } catch (error) {
      console.error('❌ 导出文件不存在:', filePath);
      return NextResponse.json(
        { error: "导出文件不存在或已过期" },
        { status: 404 }
      );
    }

    // 读取文件
    const fileBuffer = await fs.readFile(filePath);
    const stats = await fs.stat(filePath);

    console.log('✅ Video-Flow 导出视频下载成功:', {
      exportId,
      fileSize: stats.size,
      filePath
    });

    // 返回文件流
    return new NextResponse(fileBuffer, {
      headers: {
        'Content-Type': 'video/mp4',
        'Content-Length': stats.size.toString(),
        'Content-Disposition': `attachment; filename="video-flow-ai-edited-${exportId}.mp4"`,
        'Cache-Control': 'public, max-age=3600', // 缓存1小时
      },
    });

  } catch (error) {
    console.error('❌ Video-Flow 导出视频下载失败:', error);
    
    return NextResponse.json(
      { 
        error: "下载失败", 
        message: error instanceof Error ? error.message : "未知错误" 
      },
      { status: 500 }
    );
  }
}

/**
 * 清理过期的导出文件
 * 可以通过定时任务调用此函数
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: { exportId: string } }
) {
  try {
    const { exportId } = params;
    
    if (!exportId) {
      return NextResponse.json(
        { error: "导出ID不能为空" },
        { status: 400 }
      );
    }

    const workDir = join(tmpdir(), `video-flow-ai-export-${exportId}`);
    
    try {
      await fs.rm(workDir, { recursive: true, force: true });
      console.log('🗑️ 清理导出文件成功:', workDir);
      
      return NextResponse.json({
        success: true,
        message: "导出文件清理成功"
      });
    } catch (error) {
      console.warn('⚠️ 清理导出文件失败:', error);
      
      return NextResponse.json({
        success: false,
        message: "文件不存在或已被清理"
      });
    }

  } catch (error) {
    console.error('❌ 清理导出文件失败:', error);
    
    return NextResponse.json(
      { 
        error: "清理失败", 
        message: error instanceof Error ? error.message : "未知错误" 
      },
      { status: 500 }
    );
  }
}


