/**
 * 视频编辑点API路由
 * 提供编辑点的CRUD操作
 */

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

// 临时内存存储（生产环境应使用数据库）
let editPointsStorage: EditPoint[] = [];
let idCounter = 1;

/**
 * 获取编辑点列表
 * GET /api/video-edit/edit-points?video_id=xxx&project_id=xxx
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const videoId = searchParams.get('video_id');
    const projectId = searchParams.get('project_id');
    const offset = parseInt(searchParams.get('offset') || '0');
    const limit = parseInt(searchParams.get('limit') || '50');

    console.log('📋 获取编辑点列表请求:', { videoId, projectId, offset, limit });

    if (!videoId || !projectId) {
      return NextResponse.json({
        code: 400,
        successful: false,
        message: 'video_id and project_id are required',
        data: null
      }, { status: 400 });
    }

    // 过滤匹配的编辑点
    const filteredPoints = editPointsStorage.filter(point => 
      point.videoId === videoId && point.projectId === projectId
    );

    // 分页
    const paginatedPoints = filteredPoints.slice(offset, offset + limit);

    // 转换为API响应格式
    const apiPoints = paginatedPoints.map(point => ({
      id: point.id,
      video_id: point.videoId,
      project_id: point.projectId,
      user_id: point.userId,
      position_x: point.position.x,
      position_y: point.position.y,
      timestamp: point.timestamp,
      description: point.description,
      status: point.status,
      created_at: point.createdAt,
      updated_at: point.updatedAt
    }));

    const response = {
      code: 0,
      successful: true,
      message: 'Success',
      data: {
        edit_points: apiPoints,
        total_count: filteredPoints.length,
        has_more: offset + limit < filteredPoints.length
      }
    };

    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 });
  }
}

/**
 * 创建编辑点
 * POST /api/video-edit/edit-points
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { video_id, project_id, position_x, position_y, timestamp, description, status } = body;

    console.log('📝 创建编辑点请求:', body);

    if (!video_id || !project_id || position_x === undefined || position_y === undefined || timestamp === undefined) {
      return NextResponse.json({
        code: 400,
        successful: false,
        message: 'Missing required fields',
        data: null
      }, { status: 400 });
    }

    // 创建新编辑点
    const newEditPoint: EditPoint = {
      id: `edit-point-${idCounter++}`,
      videoId: video_id,
      projectId: project_id,
      userId: 1, // 从认证中获取，这里暂时硬编码
      position: {
        x: position_x,
        y: position_y
      },
      timestamp,
      description: description || '',
      status: status || EditPointStatus.PENDING,
      createdAt: Date.now(),
      updatedAt: Date.now(),
      showInput: false,
      connectionDirection: 'auto'
    };

    // 存储编辑点
    editPointsStorage.push(newEditPoint);

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

    const response = {
      code: 0,
      successful: true,
      message: 'Edit point created 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 (with body)
 */
export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json();
    const { edit_point_ids } = body;

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

    if (!edit_point_ids || !Array.isArray(edit_point_ids)) {
      return NextResponse.json({
        code: 400,
        successful: false,
        message: 'edit_point_ids array is required',
        data: null
      }, { status: 400 });
    }

    // 删除指定的编辑点
    const initialLength = editPointsStorage.length;
    editPointsStorage = editPointsStorage.filter(point => !edit_point_ids.includes(point.id));
    const deletedCount = initialLength - editPointsStorage.length;

    const response = {
      code: 0,
      successful: true,
      message: `Successfully deleted ${deletedCount} edit points`,
      data: { deleted_count: deletedCount }
    };

    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 });
  }
}
