/**
 * DELETE /api/social/accounts/[id]
 * Disconnect (revoke) a social media account
 *
 * Migration example: converted from direct NextAuth -> auth-adapter pattern.
 * Pattern: use `withAuthRoute` from `lib/auth-migration` instead of
 * importing `auth` + `getAuthenticatedUser` separately.
 *
 * user.id  replaces the old  user.userId  from getAuthenticatedUser().
 *
 * Data-source routing: WU-06 — Convex branch added for social domain.
 */

import { NextRequest, NextResponse } from "next/server";
import { withAuthRoute } from "@/lib/auth-migration";
import {
  getAccountById,
  revokeAccess,
} from "@/lib/services/social-auth.service";
import { getDataSource } from "@/lib/data-source";
import { logger } from "@/lib/logger";

export const DELETE = withAuthRoute<{ id: string }>(
  async (request: NextRequest, { params }, user) => {
    try {
      const { id } = await params;

      // -- Convex data-source branch ------------------------------------------
      if (getDataSource("social") === "convex") {
        try {
          const { convexQuery, convexMutation } =
            await import("@/lib/convex-client");

          const convexAccount = await convexQuery(
            "social/queries:getAccountById",
            { accountId: id, userId: user.id },
          );

          if (!convexAccount) {
            return NextResponse.json(
              { success: false, error: "Account not found" },
              { status: 404 },
            );
          }

          // Revoke platform access (external API call) stays as-is via service
          // then delete from Convex DB
          try {
            await revokeAccess(id);
          } catch {
            // revokeAccess may fail on Prisma lookup if the account only
            // exists in Convex — that's fine, we still delete from Convex.
            logger.warn("Prisma revokeAccess skipped (Convex-only account)", {
              id,
            });
          }

          await convexMutation("social/mutations:deleteAccount", {
            id: (convexAccount as Record<string, unknown>)._id as any,
          });

          return NextResponse.json({
            success: true,
            message: "Account disconnected",
          });
        } catch (error) {
          logger.warn("[Convex fallback] social accounts DELETE:", {
            error: error instanceof Error ? error.message : String(error),
          });
          // Fall through to Prisma path
        }
      }

      // -- Prisma path (default) -----------------------------------------------
      const account = await getAccountById(id, user.id);
      if (!account) {
        return NextResponse.json(
          { success: false, error: "Account not found" },
          { status: 404 },
        );
      }

      await revokeAccess(id);
      return NextResponse.json({
        success: true,
        message: "Account disconnected",
      });
    } catch (error) {
      logger.error("Failed to disconnect social account", { error });
      return NextResponse.json(
        { success: false, error: "Failed to disconnect account" },
        { status: 500 },
      );
    }
  },
);
