import { NextResponse } from "next/server";
import type { DocumentTableSnapshot, TableRowData } from "@/types/online-table";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { api } from "@/lib/convex/api";

interface RouteContext {
  params: Promise<{
    tableId: string;
  }>;
}

type UpdateTableRequest = {
  title?: string;
  snapshot?: DocumentTableSnapshot | null;
  rows?: TableRowData[];
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  viewPreferences?: Record<string, any>;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  schema?: Record<string, any>;
};

const extractTableId = async (context: RouteContext) => {
  return (await context.params).tableId;
};

export async function GET(_request: Request, context: RouteContext) {
  const tableId = await extractTableId(context);
  if (!tableId) {
    return NextResponse.json({ error: "Missing tableId" }, { status: 400 });
  }

  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    try {
      const table = await client.query(api.tables.get, {
        userId: auth.userId,
        tableId,
      });

      if (!table) {
        return NextResponse.json({ error: "Table not found" }, { status: 404 });
      }

      return NextResponse.json(table, { status: 200 });
    } catch (error) {
      console.error("Convex API error:", error);
      return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
  }

  return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
}

export async function PATCH(request: Request, context: RouteContext) {
  const tableId = await extractTableId(context);
  if (!tableId) {
    return NextResponse.json({ error: "Missing tableId" }, { status: 400 });
  }

  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    let body: UpdateTableRequest;
    try {
      body = (await request.json()) as UpdateTableRequest;
    } catch (error) {
      console.error("Invalid payload:", error);
      return NextResponse.json({ error: "Invalid payload" }, { status: 400 });
    }

    try {
      await client.mutation(api.tables.update, {
        userId: auth.userId,
        tableId,
        title: body.title,
        schema: body.schema,
        view_preferences: body.viewPreferences,
        snapshot: body.snapshot,
        rows: body.rows,
      });

      const updated = await client.query(api.tables.get, {
        userId: auth.userId,
        tableId,
      });

      return NextResponse.json(updated, { status: 200 });
    } catch (error) {
      console.error("Convex API error:", error);
      return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
  }

  return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
}

export async function DELETE(_request: Request, context: RouteContext) {
  const tableId = await extractTableId(context);
  if (!tableId) {
    return NextResponse.json({ error: "Missing tableId" }, { status: 400 });
  }

  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    try {
      // 软删除：进入垃圾桶（可恢复）
      await client.mutation(api.tables.remove, {
        userId: auth.userId,
        tableId,
      });

      return NextResponse.json({ success: true }, { status: 200 });
    } catch (error) {
      console.error("Convex API error:", error);
      return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
  }

  return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
}
