/**
 * N8N Credentials API
 *
 * Securely provides decrypted API keys to N8N workflows.
 * Only returns credentials for users with active workflows.
 *
 * Security measures:
 * - Requires N8N auth token
 * - Validates user has active workflow
 * - Logs all access for audit
 * - Short-lived credential responses
 */

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { apiKeyManagementService } from "@/lib/services/api-key-management.service";
import { systemSettingsService } from "@/lib/services/system-settings.service";

interface CredentialResponse {
  success: boolean;
  credential?: string;
  expires_in?: number; // Seconds
  error?: string;
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ userId: string; service: string }> },
) {
  try {
    const { userId, service } = await params;

    // Extract auth token from header
    const authHeader = request.headers.get("Authorization");
    const authToken = authHeader?.replace("Bearer ", "");

    // Validate auth token (from database or env fallback)
    const isValidToken = await systemSettingsService.validateN8NToken(
      authToken || "",
    );
    if (!isValidToken) {
      logger.warn("N8N credentials request with invalid auth token", {
        userId,
        service,
      });
      return NextResponse.json<CredentialResponse>(
        { success: false, error: "Invalid authentication token" },
        { status: 401 },
      );
    }

    // Get purpose from query params for audit logging
    const purpose =
      request.nextUrl.searchParams.get("purpose") || "n8n_workflow";

    // Validate user exists and has active subscription
    const user = await prisma.users.findUnique({
      where: { id: userId },
      include: {
        subscriptions: {
          where: { status: { in: ["active", "trialing"] } },
          take: 1,
        },
        workflows: {
          where: { status: "active" },
          take: 1,
        },
      },
    });

    if (!user) {
      logger.warn("N8N credentials request for non-existent user", {
        userId,
        service,
      });
      return NextResponse.json<CredentialResponse>(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    // Check if user is active
    if (!user.isActive) {
      logger.warn("N8N credentials request for inactive user", {
        userId,
        service,
      });
      return NextResponse.json<CredentialResponse>(
        { success: false, error: "User account is inactive" },
        { status: 403 },
      );
    }

    // Check for active subscription
    if (user.subscriptions.length === 0) {
      logger.warn("N8N credentials request for user without subscription", {
        userId,
        service,
      });
      return NextResponse.json<CredentialResponse>(
        { success: false, error: "No active subscription" },
        { status: 403 },
      );
    }

    // Check for active workflow
    if (user.workflows.length === 0) {
      logger.warn("N8N credentials request for user without active workflow", {
        userId,
        service,
      });
      return NextResponse.json<CredentialResponse>(
        { success: false, error: "No active workflow" },
        { status: 403 },
      );
    }

    // Get decrypted API key
    const credential = await apiKeyManagementService.getDecryptedAPIKey(
      userId,
      service,
    );

    if (!credential) {
      logger.info("N8N credentials request - key not found", {
        userId,
        service,
      });
      return NextResponse.json<CredentialResponse>(
        { success: false, error: `No ${service} API key configured` },
        { status: 404 },
      );
    }

    // Log access for audit
    logger.info("N8N credentials accessed", {
      userId,
      service,
      purpose,
      ip: request.headers.get("x-forwarded-for") || "unknown",
    });

    // Return credential with short expiry recommendation
    return NextResponse.json<CredentialResponse>({
      success: true,
      credential,
      expires_in: 300, // Recommend refresh every 5 minutes
    });
  } catch (error) {
    logger.error("N8N credentials error", { error });
    return NextResponse.json<CredentialResponse>(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

// Only allow GET method
export async function POST() {
  return NextResponse.json({ error: "Method not allowed" }, { status: 405 });
}
