/**
 * Organization API
 * GET - Fetch current user's organization with members
 *
 * Authentication: Required (NextAuth or auth_token cookie)
 * Authorization: Any authenticated user
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedEmail } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { convexMutation, convexQuery } from "@/lib/convex-client";

/**
 * GET /api/organization
 * Returns user's organization with members and seat configuration
 * Auto-creates organization for tier3+ users if they don't have one
 */
export async function GET(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // Get user from Convex by email
    const convexUser = await convexQuery<{
      _id: string;
      appUserId?: string;
      prismaId?: string;
      name?: string;
      companyName?: string;
      email: string;
    }>("auth/queries:getUserByEmail", { email: userEmail });

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

    // Use appUserId or prismaId for organization lookups (matches org_members.userId)
    const userId =
      convexUser.appUserId || convexUser.prismaId || convexUser._id;

    // Try Convex — returns full org state in one query
    const state = await convexQuery<{
      organization: Record<string, unknown>;
      members: unknown[];
      pendingInvitations: unknown[];
      seatConfig: Record<string, unknown>;
      userRole: string;
    }>("organizations/queries:getOrganizationStateByUserId", {
      userId,
    });

    if (state) {
      // Flatten nested user data into member objects for TeamPanel compatibility
      const flatMembers = Array.isArray(state.members)
        ? state.members.map((m: Record<string, unknown>) => {
            const user = m.user as Record<string, unknown> | null;
            return {
              id: m.id,
              userId: m.userId,
              email: user?.email || "",
              name: user?.name || "",
              role: m.role,
              joinedAt: m.joinedAt,
              lastActiveAt: m.lastActiveAt || null,
            };
          })
        : [];

      return NextResponse.json({
        success: true,
        organization: state.organization,
        members: flatMembers,
        pendingInvitations: state.pendingInvitations,
        seatConfig: state.seatConfig,
        userRole: state.userRole,
      });
    }

    // No org found — check if user qualifies for auto-creation (tier3+)
    const subscription = await convexQuery<{
      tierId?: string;
    }>("billing/queries:getActiveSubscription", { userId });

    const tierId = subscription?.tierId || "tier1";
    const isTier3Plus = ["tier3", "tier4", "tier5"].includes(tierId);

    if (!isTier3Plus) {
      return NextResponse.json(
        {
          success: false,
          error: "No organization found",
          hasOrganization: false,
        },
        { status: 404 },
      );
    }

    // Auto-create organization for tier3+ users
    const orgName =
      convexUser.companyName || convexUser.name || "My Organization";
    logger.info(
      "[Organization API] Auto-creating organization for tier3+ user",
      { userId, tierId, orgName },
    );

    try {
      await convexMutation("organizations/mutations:createOrganization", {
        ownerId: userId,
        name: orgName,
        subscriptionTier: tierId,
      });
    } catch (createError: unknown) {
      const errorMessage =
        createError instanceof Error
          ? createError.message
          : String(createError);
      if (errorMessage === "Organization feature not yet enabled") {
        return NextResponse.json(
          {
            success: false,
            error: "Organization feature not yet enabled",
            hasOrganization: false,
          },
          { status: 404 },
        );
      }
      throw createError;
    }

    // Re-fetch after creation
    const newState = await convexQuery<{
      organization: Record<string, unknown>;
      members: unknown[];
      pendingInvitations: unknown[];
      seatConfig: Record<string, unknown>;
      userRole: string;
    }>("organizations/queries:getOrganizationStateByUserId", {
      userId,
    });

    if (newState) {
      const flatMembers = Array.isArray(newState.members)
        ? newState.members.map((m: Record<string, unknown>) => {
            const user = m.user as Record<string, unknown> | null;
            return {
              id: m.id,
              userId: m.userId,
              email: user?.email || "",
              name: user?.name || "",
              role: m.role,
              joinedAt: m.joinedAt,
              lastActiveAt: m.lastActiveAt || null,
            };
          })
        : [];

      return NextResponse.json({
        success: true,
        organization: newState.organization,
        members: flatMembers,
        pendingInvitations: newState.pendingInvitations,
        seatConfig: newState.seatConfig,
        userRole: newState.userRole,
      });
    }

    // Fallback if Convex create succeeded but query returned null
    return NextResponse.json(
      {
        success: false,
        error: "Organization created but could not be loaded",
        hasOrganization: false,
      },
      { status: 404 },
    );
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error("[Organization API] Failed to fetch organization", error);

    return NextResponse.json(
      {
        success: false,
        error: errorMessage || "Failed to fetch organization",
      },
      { status: 500 },
    );
  }
}
