/* eslint-disable no-eval */
import { NextRequest, NextResponse } from "next/server";
const fs = eval('require("fs")') as typeof import("fs");
import { isValidBotName, getBotEnvFile, getBotDir } from "@/lib/paths";

/**
 * Parse a .env file into key-value pairs.
 */
function parseEnvFile(content: string): Record<string, string> {
  const result: Record<string, string> = {};

  for (const line of content.split("\n")) {
    const trimmed = line.trim();
    // Skip empty lines and comments
    if (!trimmed || trimmed.startsWith("#")) continue;

    const eqIndex = trimmed.indexOf("=");
    if (eqIndex === -1) continue;

    const key = trimmed.substring(0, eqIndex).trim();
    let value = trimmed.substring(eqIndex + 1).trim();

    // Remove surrounding quotes if present
    if (
      (value.startsWith('"') && value.endsWith('"')) ||
      (value.startsWith("'") && value.endsWith("'"))
    ) {
      value = value.slice(1, -1);
    }

    result[key] = value;
  }

  return result;
}

/**
 * Mask sensitive token values, showing only the last 4 characters.
 */
function maskSensitiveValues(
  env: Record<string, string>
): Record<string, string> {
  const sensitiveKeys = ["TOKEN", "SECRET", "KEY", "PASSWORD", "PASS", "AUTH"];
  const masked: Record<string, string> = {};

  for (const [key, value] of Object.entries(env)) {
    const upperKey = key.toUpperCase();
    const isSensitive = sensitiveKeys.some((sk) => upperKey.includes(sk));

    if (isSensitive && value.length > 4) {
      masked[key] = "•".repeat(value.length - 4) + value.slice(-4);
    } else {
      masked[key] = value;
    }
  }

  return masked;
}

/**
 * Serialize key-value pairs to .env file format.
 */
function serializeEnv(env: Record<string, string>): string {
  return (
    Object.entries(env)
      .map(([key, value]) => {
        // Quote values that contain spaces or special characters
        if (value.includes(" ") || value.includes("#") || value.includes("=")) {
          return `${key}="${value}"`;
        }
        return `${key}=${value}`;
      })
      .join("\n") + "\n"
  );
}

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

    if (!isValidBotName(botName)) {
      return NextResponse.json(
        { error: `Invalid bot name: ${botName}` },
        { status: 400 }
      );
    }

    const envFile = getBotEnvFile(botName);

    if (!fs.existsSync(envFile)) {
      return NextResponse.json({
        config: {},
        message: "No .env file found. You may need to create one from .env.example.",
      });
    }

    const content = fs.readFileSync(envFile, "utf-8");
    const env = parseEnvFile(content);
    const maskedEnv = maskSensitiveValues(env);

    return NextResponse.json({ config: maskedEnv });
  } catch (error) {
    return NextResponse.json(
      {
        error: `Failed to read config: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 }
    );
  }
}

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

    if (!isValidBotName(botName)) {
      return NextResponse.json(
        { success: false, error: `Invalid bot name: ${botName}` },
        { status: 400 }
      );
    }

    const botDir = getBotDir(botName);
    if (!fs.existsSync(botDir)) {
      return NextResponse.json(
        { success: false, error: `Bot directory not found: ${botDir}` },
        { status: 404 }
      );
    }

    const body = await request.json();

    if (!body || typeof body !== "object" || Array.isArray(body)) {
      return NextResponse.json(
        {
          success: false,
          error: "Request body must be a JSON object of key-value pairs",
        },
        { status: 400 }
      );
    }

    // Read existing .env to preserve values not being updated
    const envFile = getBotEnvFile(botName);
    let existingEnv: Record<string, string> = {};

    if (fs.existsSync(envFile)) {
      const content = fs.readFileSync(envFile, "utf-8");
      existingEnv = parseEnvFile(content);
    }

    // Merge new values (skip masked values that weren't actually changed)
    for (const [key, value] of Object.entries(body)) {
      if (typeof value !== "string") continue;
      // Skip if the value looks like a masked token (contains bullet chars)
      if (value.includes("•")) continue;
      existingEnv[key] = value;
    }

    // Write the .env file
    const envContent = serializeEnv(existingEnv);
    fs.writeFileSync(envFile, envContent, "utf-8");

    return NextResponse.json({
      success: true,
      message: `Configuration updated for ${botName}. Restart the bot for changes to take effect.`,
    });
  } catch (error) {
    return NextResponse.json(
      {
        success: false,
        error: `Failed to update config: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 }
    );
  }
}
