/**
 * GET /api/dashboard/access
 * Check if user has access to the dashboard
 * Returns access status and subscription details
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { checkDashboardAccess } from "@/lib/dashboard-access";
import { logger } from "@/lib/logger";

export async function GET(request: NextRequest) {
  try {
    // Get authenticated session
    const session = await auth();

    if (!session?.user?.id) {
      logger.warn("Dashboard access check: no authentication");
      return NextResponse.json(
        {
          hasAccess: false,
          reason: "Not authenticated",
          redirectUrl: "/en/login",
        },
        { status: 401 },
      );
    }

    // Check dashboard access
    const accessStatus = await checkDashboardAccess(session.user.id);

    // Log access attempt
    if (!accessStatus.hasAccess) {
      logger.info("Dashboard access denied", {
        userId: session.user.id,
        reason: accessStatus.reason,
      });
    }

    return NextResponse.json(accessStatus);
  } catch (error) {
    logger.error("Dashboard access check error", { error });
    return NextResponse.json(
      {
        hasAccess: false,
        reason: "System error",
        redirectUrl: "/en/login",
      },
      { status: 500 },
    );
  }
}
