/**
 * Customer Directory API
 * GET  - Fetch all customers for the authenticated user (paginated)
 * POST - Create a new customer
 *
 * All data access goes through Convex. No Prisma fallback.
 */

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

/** Shape returned by Convex getCustomers query */
interface ConvexCustomersResult {
  customers: Record<string, unknown>[];
  total: number;
  page: number;
  totalPages: number;
}

/**
 * Look up the user by email via Convex.
 */
async function findUserByEmail(email: string) {
  const user = await convexQuery<Record<string, unknown>>(
    "auth/queries:getUserByEmail",
    { email },
  );
  if (!user) return null;
  return {
    id:
      (user.prismaId as string) ||
      (user.appUserId as string) ||
      (user._id as string),
    email: user.email as string,
  };
}

/**
 * Get effective owner ID — for org members, return the org owner's user ID.
 * Uses Convex organization state lookup.
 */
async function getEffectiveOwnerIdDirect(userId: string): Promise<string> {
  try {
    const orgState = await convexQuery<Record<string, unknown>>(
      "organizations/queries:getOrganizationStateByUserId",
      { userId },
    );
    if (!orgState) return userId;

    const userRole = orgState.userRole as string | undefined;
    const organization = orgState.organization as
      | Record<string, unknown>
      | undefined;

    if (!organization || userRole === "OWNER") return userId;

    const ownerId = organization.ownerId as string | undefined;
    return ownerId || userId;
  } catch {
    return userId;
  }
}

/**
 * GET /api/user/customers
 * Returns all customers for the authenticated user with pagination.
 */
export async function GET(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

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

    const user = await findUserByEmail(userEmail);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerIdDirect(user.id);

    // Parse pagination params
    const url = new URL(request.url);
    const page = Math.max(1, parseInt(url.searchParams.get("page") || "1", 10));
    const limit = Math.min(
      100,
      Math.max(1, parseInt(url.searchParams.get("limit") || "50", 10)),
    );
    const search = url.searchParams.get("search") || "";

    const convexResult = await convexQuery<ConvexCustomersResult>(
      "customers/queries:getCustomers",
      {
        userId: effectiveUserId,
        page,
        limit,
        ...(search.trim() ? { search: search.trim() } : {}),
      },
    );

    if (convexResult) {
      return NextResponse.json({
        success: true,
        customers: convexResult.customers,
        total: convexResult.total,
        page: convexResult.page,
        limit,
        totalPages: convexResult.totalPages,
      });
    }

    // Convex returned null — return empty data
    return NextResponse.json({
      success: true,
      customers: [],
      total: 0,
      page,
      limit,
      totalPages: 0,
    });
  } catch (error) {
    logger.error(
      "Failed to fetch customers",
      error instanceof Error ? error : new Error(String(error)),
    );
    const errorMessage =
      process.env.NODE_ENV === "development"
        ? error instanceof Error
          ? error.message
          : String(error)
        : "Internal server error";
    return NextResponse.json(
      { success: false, error: errorMessage },
      { status: 500 },
    );
  }
}

/**
 * POST /api/user/customers
 * Creates a new customer via Convex.
 */
export async function POST(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

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

    // CSRF protection (bypass in development)
    if (process.env.NODE_ENV !== "development") {
      const isValidCSRF = validateCSRFToken(request);
      if (!isValidCSRF) {
        return NextResponse.json(
          { success: false, error: "Invalid CSRF token" },
          { status: 403 },
        );
      }
    }

    const user = await findUserByEmail(userEmail);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerIdDirect(user.id);

    const body = await request.json();
    const { name, phone, email, notes } = body;

    // Validation
    const errors: string[] = [];
    if (!name || name.trim().length < 2) {
      errors.push("Name must be at least 2 characters");
    }
    if (!phone || phone.trim().length < 5) {
      errors.push("Phone number is required");
    }
    if (email && !validator.isEmail(email)) {
      errors.push("Invalid email format");
    }
    if (errors.length > 0) {
      return NextResponse.json(
        { success: false, error: errors.join(", "), errors },
        { status: 400 },
      );
    }

    try {
      const convexId = await convexMutation<string>(
        "customers/mutations:createCustomer",
        {
          userId: effectiveUserId,
          name: name.trim(),
          phone: phone.trim(),
          ...(email ? { email: email.trim() } : {}),
          ...(notes ? { notes: notes.trim() } : {}),
        },
      );

      if (convexId) {
        // Fetch the created customer back from Convex for the response
        const created = await convexQuery("customers/queries:getCustomerById", {
          id: convexId,
          userId: effectiveUserId,
        });
        return NextResponse.json(
          { success: true, customer: created ?? { _id: convexId } },
          { status: 201 },
        );
      }

      // Convex returned null
      return NextResponse.json(
        { success: false, error: "Failed to create customer" },
        { status: 503 },
      );
    } catch (convexErr) {
      // Check for duplicate phone error from Convex
      if (
        convexErr instanceof Error &&
        convexErr.message.includes("DUPLICATE_PHONE")
      ) {
        return NextResponse.json(
          {
            success: false,
            error: "A customer with this phone number already exists",
          },
          { status: 409 },
        );
      }
      throw convexErr;
    }
  } catch (error) {
    logger.error(
      "Failed to create customer",
      error instanceof Error ? error : new Error(String(error)),
    );
    return NextResponse.json(
      { success: false, error: "Failed to create customer" },
      { status: 500 },
    );
  }
}
