import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/core/storage/prisma";

/**
 * Strip heavy base64 data from JSON values to enable fast list loading.
 * Targets: attachments[].data, versions[].fileData, and any top-level `data`
 * field that looks like base64 (>1KB). Replaces with "__stripped__" marker.
 */
function stripHeavyFields(value: unknown): unknown {
  if (!value || typeof value !== "object") return value;
  if (Array.isArray(value)) return value.map(stripHeavyFields);

  const obj = value as Record<string, unknown>;
  const result: Record<string, unknown> = {};

  for (const [k, v] of Object.entries(obj)) {
    if (k === "data" && typeof v === "string" && v.length > 1024) {
      // Strip large base64 data fields, keep a marker
      result[k] = "__stripped__";
    } else if (k === "fileData" && typeof v === "string" && v.length > 1024) {
      result[k] = "__stripped__";
    } else if (Array.isArray(v)) {
      result[k] = v.map(stripHeavyFields);
    } else if (v && typeof v === "object") {
      result[k] = stripHeavyFields(v);
    } else {
      result[k] = v;
    }
  }
  return result;
}

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const namespace = searchParams.get("namespace");
  const key = searchParams.get("key");
  const lightweight = searchParams.get("lightweight") === "true";

  if (!namespace) {
    return NextResponse.json(
      { error: "Namespace is required" },
      { status: 400 },
    );
  }

  try {
    if (key) {
      // Get single item
      const item = await prisma.keyValueStore.findUnique({
        where: {
          namespace_key: {
            namespace,
            key,
          },
        },
      });
      return NextResponse.json({ value: item ? item.value : null });
    } else {
      // Get all items in namespace
      const result: Record<string, unknown> = {};

      // Use Prisma SELECT with only key+value columns (no id/timestamps)
      const items = await prisma.keyValueStore.findMany({
        where: { namespace },
        select: { key: true, value: true },
      });
      for (const item of items) {
        result[item.key] = lightweight
          ? stripHeavyFields(item.value)
          : item.value;
      }

      return NextResponse.json({ items: result });
    }
  } catch (error) {
    console.error("Storage GET error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { namespace, key, value } = body;

    if (!namespace || !key) {
      return NextResponse.json(
        { error: "Namespace and key are required" },
        { status: 400 },
      );
    }

    await prisma.keyValueStore.upsert({
      where: {
        namespace_key: {
          namespace,
          key,
        },
      },
      update: {
        value,
      },
      create: {
        namespace,
        key,
        value,
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Storage POST error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function DELETE(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const namespace = searchParams.get("namespace");
  const key = searchParams.get("key");

  if (!namespace) {
    return NextResponse.json(
      { error: "Namespace is required" },
      { status: 400 },
    );
  }

  try {
    if (key) {
      // Delete single item
      await prisma.keyValueStore
        .delete({
          where: {
            namespace_key: {
              namespace,
              key,
            },
          },
        })
        .catch((err: { code?: string }) => {
          if (err.code !== "P2025") throw err;
        });
    } else {
      // Clear namespace
      await prisma.keyValueStore.deleteMany({
        where: { namespace },
      });
    }
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Storage DELETE error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
