/**
 * 单个编辑点API路由
 * 提供单个编辑点的更新和删除操作
 */

import { NextRequest, NextResponse } from 'next/server';
import { EditPoint, EditPointStatus } from '@/components/pages/work-flow/video-edit/types';

// 引用主路由的存储（实际应用中应使用共享数据库）
// 这里我们需要一个简单的方式来共享数据
let editPointsStorage: EditPoint[] = [];

// 获取存储的辅助函数
function getEditPointsStorage(): EditPoint[] {
  // 在实际应用中，这里应该从数据库获取
  return editPointsStorage;
}

function setEditPointsStorage(points: EditPoint[]): void {
  // 在实际应用中，这里应该保存到数据库
  editPointsStorage = points;
}

/**
 * 更新编辑点
 * PUT /api/video-edit/edit-points/[id]
 */
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;
    const body = await request.json();
    const { description, status, position_x, position_y } = body;

    console.log('✏️ 更新编辑点请求:', { id, body });

    if (!id) {
      return NextResponse.json({
        code: 400,
        successful: false,
        message: 'Edit point ID is required',
        data: null
      }, { status: 400 });
    }

    const storage = getEditPointsStorage();
    const editPointIndex = storage.findIndex(point => point.id === id);

    if (editPointIndex === -1) {
      return NextResponse.json({
        code: 404,
        successful: false,
        message: 'Edit point not found',
        data: null
      }, { status: 404 });
    }

    // 更新编辑点
    const editPoint = storage[editPointIndex];
    
    if (description !== undefined) {
      editPoint.description = description;
    }
    
    if (status !== undefined) {
      editPoint.status = status;
    }
    
    if (position_x !== undefined && position_y !== undefined) {
      editPoint.position = { x: position_x, y: position_y };
    }
    
    editPoint.updatedAt = Date.now();

    // 保存更新
    setEditPointsStorage(storage);

    // 转换为API响应格式
    const apiResponse = {
      id: editPoint.id,
      videoId: editPoint.videoId,
      projectId: editPoint.projectId,
      userId: editPoint.userId,
      position: editPoint.position,
      timestamp: editPoint.timestamp,
      description: editPoint.description,
      status: editPoint.status,
      createdAt: editPoint.createdAt,
      updatedAt: editPoint.updatedAt
    };

    const response = {
      code: 0,
      successful: true,
      message: 'Edit point updated successfully',
      data: apiResponse
    };

    console.log('✅ 编辑点更新成功:', response.data);
    return NextResponse.json(response);

  } catch (error) {
    console.error('❌ 更新编辑点失败:', error);
    return NextResponse.json({
      code: 500,
      successful: false,
      message: 'Internal server error',
      data: null
    }, { status: 500 });
  }
}

/**
 * 删除编辑点
 * DELETE /api/video-edit/edit-points/[id]
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;

    console.log('🗑️ 删除编辑点请求:', { id });

    if (!id) {
      return NextResponse.json({
        code: 400,
        successful: false,
        message: 'Edit point ID is required',
        data: null
      }, { status: 400 });
    }

    const storage = getEditPointsStorage();
    const editPointIndex = storage.findIndex(point => point.id === id);

    if (editPointIndex === -1) {
      return NextResponse.json({
        code: 404,
        successful: false,
        message: 'Edit point not found',
        data: null
      }, { status: 404 });
    }

    // 删除编辑点
    storage.splice(editPointIndex, 1);
    setEditPointsStorage(storage);

    const response = {
      code: 0,
      successful: true,
      message: 'Edit point deleted successfully',
      data: null
    };

    console.log('✅ 编辑点删除成功');
    return NextResponse.json(response);

  } catch (error) {
    console.error('❌ 删除编辑点失败:', error);
    return NextResponse.json({
      code: 500,
      successful: false,
      message: 'Internal server error',
      data: null
    }, { status: 500 });
  }
}

/**
 * 提交编辑请求
 * POST /api/video-edit/edit-points/[id]/submit
 */
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;

    console.log('📤 提交编辑请求:', { id });

    if (!id) {
      return NextResponse.json({
        code: 400,
        successful: false,
        message: 'Edit point ID is required',
        data: null
      }, { status: 400 });
    }

    const storage = getEditPointsStorage();
    const editPointIndex = storage.findIndex(point => point.id === id);

    if (editPointIndex === -1) {
      return NextResponse.json({
        code: 404,
        successful: false,
        message: 'Edit point not found',
        data: null
      }, { status: 404 });
    }

    // 更新状态为处理中
    const editPoint = storage[editPointIndex];
    editPoint.status = EditPointStatus.PROCESSING;
    editPoint.updatedAt = Date.now();

    setEditPointsStorage(storage);

    // 这里可以添加实际的编辑处理逻辑
    // 比如发送到AI编辑服务、添加到处理队列等

    const response = {
      code: 0,
      successful: true,
      message: 'Edit request submitted successfully',
      data: null
    };

    console.log('✅ 编辑请求提交成功');
    return NextResponse.json(response);

  } catch (error) {
    console.error('❌ 提交编辑请求失败:', error);
    return NextResponse.json({
      code: 500,
      successful: false,
      message: 'Internal server error',
      data: null
    }, { status: 500 });
  }
}
