/**
 * Workflow Activation API
 *
 * POST - Activate a workflow (with tier check)
 * DELETE - Deactivate a workflow
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { WorkflowManagementService } from "@/lib/services/workflow-management.service";
import { validateCSRFToken } from "@/lib/csrf";
import { rateLimiters, applyRateLimit } from "@/lib/rate-limiter";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

const scopedLogger = logger.scope("WorkflowActivationAPI");

/**
 * POST /api/dashboard/workflows/[id]/activate
 * Activate a workflow (with tier-based access check)
 */
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    // Rate limiting
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );

    if (rateLimitResponse) {
      return rateLimitResponse;
    }

    // Authenticate user
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // CSRF protection
    if (!validateCSRFToken(request)) {
      scopedLogger.warn("CSRF validation failed", { userId: user.userId });
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const workflowId = params.id;

    // Convex data-source routing (WU-18)
    if (getDataSource("workflows") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        const result = await convexMutation(
          "workflows/mutations:activateWorkflow",
          {
            id: workflowId as any,
            userId: user.userId,
          },
        );
        if (result !== null) {
          scopedLogger.info("Workflow activated via Convex", {
            userId: user.userId,
            workflowId,
          });
          return NextResponse.json({
            success: true,
            message: "Workflow activated",
          });
        }
      } catch (convexError: any) {
        if (
          convexError?.message?.includes("not found") ||
          convexError?.message?.includes("unauthorized")
        ) {
          return NextResponse.json(
            { success: false, error: "Workflow not found or unauthorized" },
            { status: 404 },
          );
        }
        // Fall through to Prisma
      }
    }

    // Get user's package tier
    const dbUser = await prisma.users.findUnique({
      where: { id: user.userId },
      include: {
        subscriptions: {
          where: { status: "active" },
          orderBy: { createdAt: "desc" },
          take: 1,
          select: { tierId: true },
        },
      },
    });

    if (!dbUser) {
      return NextResponse.json(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    // Get tier from active subscription or fallback to selectedPackage or default
    const activeSubscription = dbUser.subscriptions?.[0];
    const packageTier =
      activeSubscription?.tierId || dbUser.selectedPackage || "tier1";

    // Activate workflow (service validates tier access)
    const result = await WorkflowManagementService.activateWorkflow(
      workflowId,
      user.userId,
      packageTier,
    );

    scopedLogger.info("Workflow activated", {
      userId: user.userId,
      workflowId,
      tier: packageTier,
    });

    return NextResponse.json({
      success: true,
      ...result,
    });
  } catch (error: any) {
    scopedLogger.error("Failed to activate workflow", error);

    // Handle tier restriction error (402 Payment Required)
    if (
      error.message?.includes("requires") &&
      error.message?.includes("tier")
    ) {
      return NextResponse.json(
        { success: false, error: error.message, upgradeRequired: true },
        { status: 402 },
      );
    }

    // Handle not found error
    if (
      error.message?.includes("not found") ||
      error.message?.includes("unauthorized")
    ) {
      return NextResponse.json(
        { success: false, error: "Workflow not found or unauthorized" },
        { status: 404 },
      );
    }

    return NextResponse.json(
      { success: false, error: "Failed to activate workflow" },
      { status: 500 },
    );
  }
}

/**
 * DELETE /api/dashboard/workflows/[id]/activate
 * Deactivate a workflow
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    // Rate limiting
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );

    if (rateLimitResponse) {
      return rateLimitResponse;
    }

    // Authenticate user
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // CSRF protection
    if (!validateCSRFToken(request)) {
      scopedLogger.warn("CSRF validation failed", { userId: user.userId });
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const workflowId = params.id;

    // Convex data-source routing (WU-18)
    if (getDataSource("workflows") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        const result = await convexMutation(
          "workflows/mutations:deactivateWorkflow",
          {
            id: workflowId as any,
            userId: user.userId,
          },
        );
        if (result !== null) {
          scopedLogger.info("Workflow deactivated via Convex", {
            userId: user.userId,
            workflowId,
          });
          return NextResponse.json({
            success: true,
            message: "Workflow deactivated",
          });
        }
      } catch (convexError: any) {
        if (
          convexError?.message?.includes("not found") ||
          convexError?.message?.includes("unauthorized")
        ) {
          return NextResponse.json(
            { success: false, error: "Workflow not found or unauthorized" },
            { status: 404 },
          );
        }
        // Fall through to Prisma
      }
    }

    // Deactivate workflow
    const result = await WorkflowManagementService.deactivateWorkflow(
      workflowId,
      user.userId,
    );

    scopedLogger.info("Workflow deactivated", {
      userId: user.userId,
      workflowId,
    });

    return NextResponse.json({
      success: true,
      ...result,
    });
  } catch (error: any) {
    scopedLogger.error("Failed to deactivate workflow", error);

    // Handle not found error
    if (
      error.message?.includes("not found") ||
      error.message?.includes("unauthorized")
    ) {
      return NextResponse.json(
        { success: false, error: "Workflow not found or unauthorized" },
        { status: 404 },
      );
    }

    return NextResponse.json(
      { success: false, error: "Failed to deactivate workflow" },
      { status: 500 },
    );
  }
}
