/**
 * GET /api/analytics/metrics
 *
 * Returns analytics metrics for the dashboard.
 * Calls getDashboardMetrics (Convex) which queries the bookings table.
 * Returns a nested DashboardMetrics shape that the UI expects.
 */

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 { convexQuery } from "@/lib/convex-client";
import { getEffectiveDataOwnerId } from "@/lib/utils/organization-data";

export const dynamic = "force-dynamic";

interface ConvexUser {
  _id: string;
  prismaId?: string;
  appUserId?: string;
  email: string;
}

interface ConvexMetrics {
  totalBookings: number;
  completedBookings: number;
  pendingBookings: number;
  cancelledBookings: number;
  noShowBookings: number;
  totalRevenue: number;
  totalCustomers: number;
  newCustomers: number;
  depositsCollected: number;
  depositsPending: number;
  averageBookingValue: number;
  completionRate: number;
  noShowRate: number;
  cancellationRate: number;
  // Quotation metrics
  quotationRevenue: number;
  quotationCount: number;
  quotationsPaid: number;
  quotationsDraft: number;
  quotationsSent: number;
  quotationsAccepted: number;
  quotationsCancelled: number;
  // Rental metrics
  rentalRevenue: number;
  activeRentals: number;
  totalRentals: number;
  // Combined total
  totalCombinedRevenue: number;
  // Outstanding receivables
  outstandingReceivables: number;
  unpaidQuotationAmount: number;
  pendingDepositAmount: number;
  overdueRentalAmount: number;
}

/** Build the zeroed nested response shape */
function buildZeroedMetrics(period: string) {
  return {
    revenue: {
      total: 0,
      currency: "QAR",
      depositsCollected: 0,
      depositsPending: 0,
    },
    bookings: {
      total: 0,
      confirmed: 0,
      pending: 0,
      completed: 0,
      cancelled: 0,
    },
    customers: { total: 0, new: 0 },
    performance: {
      completionRate: 0,
      noShowRate: 0,
      averageBookingValue: 0,
    },
    quotations: {
      revenue: 0,
      count: 0,
      paid: 0,
      draft: 0,
      sent: 0,
      accepted: 0,
      cancelled: 0,
    },
    rentals: {
      revenue: 0,
      active: 0,
      total: 0,
    },
    totalCombinedRevenue: 0,
    receivables: {
      total: 0,
      unpaidQuotations: 0,
      pendingDeposits: 0,
      overdueRentals: 0,
    },
    period,
  };
}

export async function GET(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

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

    const convexUser = await convexQuery<ConvexUser>(
      "auth/queries:getUserByEmail",
      { email: userEmail },
    );

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

    const userId =
      convexUser.prismaId || convexUser.appUserId || convexUser._id;
    const period = request.nextUrl.searchParams.get("period") || "week";

    // Resolve org membership so rentals (org-scoped) are included
    const orgResult = await getEffectiveDataOwnerId(userId);
    const organizationId = orgResult.organizationId;

    // Call getDashboardMetrics which queries bookings, quotations, and rentals
    const metrics = await convexQuery<ConvexMetrics>(
      "analytics/queries:getDashboardMetrics",
      {
        userId,
        ...(organizationId ? { organizationId } : {}),
      },
    );

    if (metrics) {
      return NextResponse.json({
        revenue: {
          total: metrics.totalCombinedRevenue,
          bookingRevenue: metrics.totalRevenue,
          quotationRevenue: metrics.quotationRevenue,
          rentalRevenue: metrics.rentalRevenue,
          currency: "QAR",
          depositsCollected: metrics.depositsCollected,
          depositsPending: metrics.depositsPending,
        },
        bookings: {
          total: metrics.totalBookings,
          confirmed: metrics.completedBookings,
          pending: metrics.pendingBookings,
          completed: metrics.completedBookings,
          cancelled: metrics.cancelledBookings,
        },
        customers: {
          total: metrics.totalCustomers,
          new: metrics.newCustomers,
        },
        performance: {
          completionRate: metrics.completionRate,
          noShowRate: metrics.noShowRate,
          averageBookingValue: metrics.averageBookingValue,
        },
        quotations: {
          revenue: metrics.quotationRevenue,
          count: metrics.quotationCount,
          paid: metrics.quotationsPaid,
          draft: metrics.quotationsDraft,
          sent: metrics.quotationsSent,
          accepted: metrics.quotationsAccepted,
          cancelled: metrics.quotationsCancelled,
        },
        rentals: {
          revenue: metrics.rentalRevenue,
          active: metrics.activeRentals,
          total: metrics.totalRentals,
        },
        totalCombinedRevenue: metrics.totalCombinedRevenue,
        receivables: {
          total: metrics.outstandingReceivables,
          unpaidQuotations: metrics.unpaidQuotationAmount,
          pendingDeposits: metrics.pendingDepositAmount,
          overdueRentals: metrics.overdueRentalAmount,
        },
        period,
      });
    }

    // Convex returned null — return zeroed metrics in the same nested shape
    return NextResponse.json(buildZeroedMetrics(period));
  } catch (error) {
    logger.error("Analytics metrics error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    });
    return NextResponse.json(
      { error: "Failed to retrieve analytics metrics" },
      { status: 500 },
    );
  }
}
