import { NextRequest, NextResponse } from 'next/server';

import { adminApiDisabledResponse, isAdminApiEnabled } from '@/lib/runtime/adminApi';

interface RouteParams {
  params: Promise<{
    id: string;
  }>;
}

// POST /api/funnels/[id]/duplicate - создать копию воронки
export async function POST(request: NextRequest, { params }: RouteParams) {
  if (!isAdminApiEnabled()) {
    return adminApiDisabledResponse();
  }

  try {
    const { id } = await params;
    const [
      { default: connectMongoDB },
      { default: FunnelModel },
      { default: FunnelHistoryModel },
    ] = await Promise.all([
      import('@/lib/mongodb'),
      import('@/lib/models/Funnel'),
      import('@/lib/models/FunnelHistory'),
    ]);

    await connectMongoDB();

    const body = await request.json();
    const { name, newFunnelId } = body;

    // Находим исходную воронку
    const sourceFunnel = await FunnelModel.findById(id);
    if (!sourceFunnel) {
      return NextResponse.json(
        { error: 'Source funnel not found' },
        { status: 404 }
      );
    }

    // Подготавливаем данные для копии
    const duplicatedFunnelData = {
      ...sourceFunnel.funnelData,
      meta: {
        ...sourceFunnel.funnelData.meta,
        id: newFunnelId || `${sourceFunnel.funnelData.meta.id}-copy-${Date.now()}`,
        title: `${sourceFunnel.funnelData.meta.title || sourceFunnel.name} (копия)`,
        description: sourceFunnel.funnelData.meta.description
      }
    };

    // Проверяем уникальность нового ID
    const existingFunnel = await FunnelModel.findOne({ 
      'funnelData.meta.id': duplicatedFunnelData.meta.id 
    });
    
    if (existingFunnel) {
      return NextResponse.json(
        { error: 'Funnel with this ID already exists' },
        { status: 409 }
      );
    }

    // Создаем копию
    const duplicatedFunnel = new FunnelModel({
      name: name || `${sourceFunnel.name} (копия)`,
      description: sourceFunnel.description,
      funnelData: duplicatedFunnelData,
      status: 'draft', // Копии всегда создаются как черновики
      version: 1,
      parentFunnelId: sourceFunnel._id, // Связываем с исходной воронкой
      usage: {
        totalViews: 0,
        totalCompletions: 0
      }
    });

    const savedFunnel = await duplicatedFunnel.save();

    // Создаем базовую точку в истории для копии
    const sessionId = `duplicate-${Date.now()}`;
    await FunnelHistoryModel.create({
      funnelId: String(savedFunnel._id),
      sessionId,
      funnelSnapshot: duplicatedFunnelData,
      actionType: 'create',
      sequenceNumber: 0,
      description: `Создана копия воронки "${sourceFunnel.name}"`,
      isBaseline: true,
      changeDetails: {
        action: 'duplicate',
        previousValue: null,
        newValue: { sourceId: sourceFunnel._id }
      }
    });

    return NextResponse.json({
      _id: savedFunnel._id,
      name: savedFunnel.name,
      description: savedFunnel.description,
      status: savedFunnel.status,
      version: savedFunnel.version,
      createdAt: savedFunnel.createdAt,
      updatedAt: savedFunnel.updatedAt,
      usage: savedFunnel.usage,
      funnelData: savedFunnel.funnelData
    }, { status: 201 });

  } catch (error) {
    console.error('POST /api/funnels/[id]/duplicate error:', error);
    
    if (error instanceof Error && error.message.includes('duplicate key')) {
      return NextResponse.json(
        { error: 'Funnel with this name already exists' },
        { status: 409 }
      );
    }
    
    return NextResponse.json(
      { error: 'Failed to duplicate funnel' },
      { status: 500 }
    );
  }
}
