/**
 * Workflows Management API
 *
 * GET - Get user workflows with tier info
 * POST - Create new workflow (with CSRF and rate limiting)
 */

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("WorkflowsAPI");

/**
 * GET /api/dashboard/workflows
 * Returns user's workflows with tier information
 */
export async function GET(request: NextRequest) {
  try {
    // Authenticate user
    const user = await getAuthenticatedUser(request, auth);

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

    // Convex data-source routing (WU-18)
    if (getDataSource("workflows") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");
        const result = await convexQuery("workflows/queries:getWorkflows", {
          userId: user.userId,
          limit: 50,
        });
        if (result !== null) {
          return NextResponse.json({
            success: true,
            workflows: result,
            allowedFeatures: [],
            currentTier: "tier1",
            totalCount: (result as unknown[]).length,
          });
        }
      } catch {
        // Fall through to Prisma
      }
    }

    // Get user's package tier from subscription
    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";

    // Get workflows with permissions
    const workflows = await WorkflowManagementService.getUserWorkflows(
      user.userId,
      packageTier,
    );

    // Get allowed features for this tier
    const allowedFeatures =
      WorkflowManagementService.getAllowedWorkflowsByTier(packageTier);

    scopedLogger.info("Workflows retrieved", {
      userId: user.userId,
      count: workflows.length,
      tier: packageTier,
    });

    return NextResponse.json({
      success: true,
      workflows,
      allowedFeatures,
      currentTier: packageTier,
      totalCount: workflows.length,
    });
  } catch (error) {
    scopedLogger.error("Failed to get workflows", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/dashboard/workflows
 * Create a new workflow
 * Requires CSRF token and rate limiting
 */
export async function POST(request: NextRequest) {
  try {
    // Rate limiting - 10 workflow creations per hour
    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 },
      );
    }

    // Parse request body
    const body = await request.json();
    const { workflowType, n8nWorkflowId, config } = body;

    // Validation
    if (!workflowType) {
      return NextResponse.json(
        { success: false, error: "Workflow type is required" },
        { status: 400 },
      );
    }

    if (!n8nWorkflowId) {
      return NextResponse.json(
        { success: false, error: "n8n workflow ID is required" },
        { status: 400 },
      );
    }

    // Convex data-source routing (WU-18)
    if (getDataSource("workflows") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        const result = await convexMutation(
          "workflows/mutations:createWorkflow",
          {
            userId: user.userId,
            workflowType,
            n8nWorkflowId,
            config: config || {},
          },
        );
        if (result !== null) {
          scopedLogger.info("Workflow created via Convex", {
            userId: user.userId,
            workflowId: result,
            workflowType,
          });
          return NextResponse.json(
            {
              success: true,
              workflow: {
                id: result,
                workflowType,
                n8nWorkflowId,
                status: "inactive",
              },
              message: "Workflow created successfully",
            },
            { status: 201 },
          );
        }
      } catch (convexError: any) {
        if (convexError?.message?.includes("already exists")) {
          return NextResponse.json(
            { success: false, error: convexError.message },
            { status: 409 },
          );
        }
        // Fall through to Prisma
      }
    }

    // Create workflow (service handles tier validation on activation)
    const workflow = await WorkflowManagementService.createWorkflow(
      user.userId,
      {
        workflowType,
        n8nWorkflowId,
        config: config || {},
      },
    );

    scopedLogger.info("Workflow created", {
      userId: user.userId,
      workflowId: workflow.id,
      workflowType,
    });

    return NextResponse.json(
      {
        success: true,
        workflow,
        message: "Workflow created successfully",
      },
      { status: 201 },
    );
  } catch (error: any) {
    scopedLogger.error("Failed to create workflow", error);

    // Handle duplicate workflow error
    if (error.message?.includes("already exists")) {
      return NextResponse.json(
        { success: false, error: error.message },
        { status: 409 },
      );
    }

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