/**
 * The Hearth - Deploy API (Preview Mode)
 * POST /api/dark-factory/deploy
 * 
 * Records deployment intent in database for preview/download.
 * Does NOT write files to the filesystem — artifacts are stored
 * in the GeneratedArtifact table and can be viewed/downloaded from the UI.
 * 
 * Filesystem deployment was removed because:
 * 1. Production filesystem is ephemeral (won't survive redeployment)
 * 2. Writing to the live codebase at runtime is a security concern
 * 3. Next.js won't serve new routes without a rebuild anyway
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { VOCAB } from '@/lib/white-label/constants';
import { requireDFAuth } from '@/lib/dark-factory/auth-guard';

export const dynamic = 'force-dynamic';

// Helper to generate app slug from project name
function generateAppSlug(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '')
    .substring(0, 50);
}

export async function POST(request: NextRequest) {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  try {
    const body = await request.json();
    
    const { taskId, artifactIds, environment = 'preview' } = body;

    if (!taskId) {
      return NextResponse.json(
        { error: 'Task ID is required' },
        { status: 400 }
      );
    }

    // Get the task with request and project info
    const task = await prisma.generationTask.findUnique({
      where: { id: taskId },
      include: { 
        artifacts: true,
        request: {
          include: {
            project: true,
          },
        },
      },
    });

    if (!task) {
      return NextResponse.json(
        { error: 'Task not found' },
        { status: 404 }
      );
    }

    // Only allow deployment for awaiting_approval or completed tasks
    if (task.status !== 'awaiting_approval' && task.status !== 'completed') {
      return NextResponse.json(
        { error: `Cannot deploy task with status: ${task.status}` },
        { status: 400 }
      );
    }

    // Filter artifacts to deploy
    const artifactsToDeploy = artifactIds 
      ? task.artifacts.filter((a: any) => artifactIds.includes(a.id))
      : task.artifacts;

    if (artifactsToDeploy.length === 0) {
      return NextResponse.json(
        { error: 'No artifacts to deploy' },
        { status: 400 }
      );
    }

    // Determine app slug from project or generate from prompt
    const project = task.request?.project;
    const appSlug = project?.slug || generateAppSlug(task.request?.prompt?.substring(0, 30) || `app-${Date.now()}`);
    const appName = project?.name || 'Generated App';

    // Create deployment record (preview mode — no filesystem writes)
    const deployment = await prisma.deployment.create({
      data: {
        taskId,
        environment: 'preview',
        artifactIds: artifactsToDeploy.map((a: any) => a.id),
        status: 'deployed',
        deployedAt: new Date(),
        logs: [
          `✓ Preview deployment created for "${appName}"`,
          `✓ ${artifactsToDeploy.length} artifacts registered`,
          `ℹ Artifacts are stored in database (preview mode — no filesystem writes)`,
          `ℹ Use the artifact viewer to browse and download generated code`,
        ],
        appSlug,
        liveUrl: null, // No live URL in preview mode
      },
    });

    // Mark artifacts as deployed (for tracking)
    for (const artifact of artifactsToDeploy) {
      await prisma.generatedArtifact.update({
        where: { id: artifact.id },
        data: { deployed: true },
      });
    }

    // Update task status
    await prisma.generationTask.update({
      where: { id: taskId },
      data: {
        status: 'completed',
        completedAt: new Date(),
      },
    });

    // Update project stats
    if (project) {
      await prisma.darkFactoryProject.update({
        where: { id: project.id },
        data: {
          artifactCount: { increment: artifactsToDeploy.length },
          lastActivityAt: new Date(),
        },
      });
    }

    // Log event
    await prisma.factoryEvent.create({
      data: {
        type: 'preview_deployment_created',
        taskId,
        payload: {
          deploymentId: deployment.id,
          artifactCount: artifactsToDeploy.length,
          appSlug,
          appName,
          mode: 'preview',
        },
      },
    });

    return NextResponse.json({
      success: true,
      deploymentId: deployment.id,
      deployed: artifactsToDeploy.length,
      failed: 0,
      appSlug,
      appName,
      mode: 'preview',
      logs: deployment.logs,
      message: `Preview deployment created with ${artifactsToDeploy.length} artifacts. Browse code in the artifact viewer.`,
      artifacts: artifactsToDeploy.map((a: any) => ({
        id: a.id,
        type: a.type,
        path: a.path,
      })),
    });

  } catch (error) {
    console.error('Deployment error:', error);
    return NextResponse.json(
      { 
        error: 'Deployment failed', 
        details: error instanceof Error ? error.message : 'Unknown error' 
      },
      { status: 500 }
    );
  }
}
