/**
 * Auth Migration Helpers
 *
 * Utilities for incrementally migrating API routes from direct NextAuth usage
 * to the dual-auth adapter pattern. Designed for the Strangler Fig migration:
 * NextAuth (Prisma) → Clerk (Convex).
 *
 * Migration steps for an API route:
 *
 *   Before (direct NextAuth):
 *     import { auth } from '@/lib/auth';
 *     import { getAuthenticatedUser } from '@/lib/utils/auth-helpers.util';
 *
 *     const user = await getAuthenticatedUser(request, auth);
 *     if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
 *     // user.userId
 *
 *   After (auth-migration adapter):
 *     import { withAuthRoute } from '@/lib/auth-migration';
 *
 *     export const GET = withAuthRoute(async (request, context, user) => {
 *       // user.id  (note: .id not .userId)
 *     });
 *
 * See `app/api/social/accounts/[id]/route.ts` for a complete example.
 */

import { NextRequest, NextResponse } from "next/server";
import { withAuth, getAuthUser, AuthAdapterUser } from "./auth-adapter";

// Re-export withAuth as withAuthRoute for route-level ergonomics
export { withAuth as withAuthRoute };
export type { AuthAdapterUser };

// ---------------------------------------------------------------------------
// migrateRoute — wrapper for the legacy (request, context) two-arg pattern
// ---------------------------------------------------------------------------

type LegacyContext<P = Record<string, string>> = { params: Promise<P> };

type MigratedHandler<P = Record<string, string>> = (
  request: NextRequest,
  context: LegacyContext<P> & { user: AuthAdapterUser },
) => Promise<NextResponse>;

/**
 * Wrap any existing Next.js App Router handler to use the dual-auth adapter.
 *
 * The injected `user` is available on the context object, preserving full
 * compatibility with existing context destructuring patterns.
 *
 * @example
 * ```typescript
 * // Before migration:
 * export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
 *   const user = await getAuthenticatedUser(request, auth);
 *   if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
 *   const { id } = await params;
 *   return NextResponse.json({ id, userId: user.userId });
 * }
 *
 * // After migration:
 * export const GET = migrateRoute<{ id: string }>(async (request, { params, user }) => {
 *   const { id } = await params;
 *   return NextResponse.json({ id, userId: user.id });
 * });
 * ```
 */
export function migrateRoute<P = Record<string, string>>(
  handler: MigratedHandler<P>,
): (request: NextRequest, context: LegacyContext<P>) => Promise<NextResponse> {
  return async (request: NextRequest, context: LegacyContext<P>) => {
    const user = await getAuthUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    return handler(request, { ...context, user });
  };
}

// ---------------------------------------------------------------------------
// requireOrgMember — shorthand that also validates organization membership
// ---------------------------------------------------------------------------

/**
 * Like migrateRoute, but additionally requires the user to belong to an org.
 * Returns 403 if the user has no organizationId.
 *
 * @example
 * ```typescript
 * export const POST = requireOrgMember<{ id: string }>(async (req, { params, user }) => {
 *   // user.organizationId is guaranteed non-null here
 * });
 * ```
 */
export function requireOrgMember<P = Record<string, string>>(
  handler: MigratedHandler<P>,
): (request: NextRequest, context: LegacyContext<P>) => Promise<NextResponse> {
  return async (request: NextRequest, context: LegacyContext<P>) => {
    const user = await getAuthUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    if (!user.organizationId) {
      return NextResponse.json(
        { error: "Organization membership required" },
        { status: 403 },
      );
    }
    return handler(request, { ...context, user });
  };
}
