/**
 * Daily Analytics API
 *
 * GET - Get daily conversation statistics
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { conversationTrackerService } from "@/lib/services/conversation-tracker.service";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

const scopedLogger = logger.scope("DailyAnalyticsAPI");

/**
 * GET /api/dashboard/analytics/daily
 * Returns daily conversation statistics
 *
 * Query Parameters:
 * - date: Date to get statistics for (ISO format YYYY-MM-DD, defaults to today)
 *
 * Example: /api/dashboard/analytics/daily?date=2025-11-25
 */
export async function GET(request: NextRequest) {
  try {
    // Authenticate user
    const user = await getAuthenticatedUser(request, auth);

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

    // Parse query parameters
    const searchParams = request.nextUrl.searchParams;
    const dateParam = searchParams.get("date");

    // Parse and validate date
    let date: Date;

    if (dateParam) {
      // Validate date format (YYYY-MM-DD)
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
      if (!dateRegex.test(dateParam)) {
        return NextResponse.json(
          {
            success: false,
            error: "Invalid date format. Use YYYY-MM-DD (e.g., 2025-11-25)",
          },
          { status: 400 },
        );
      }

      date = new Date(dateParam);

      // Check if date is valid
      if (isNaN(date.getTime())) {
        return NextResponse.json(
          { success: false, error: "Invalid date" },
          { status: 400 },
        );
      }

      // Don't allow future dates
      const today = new Date();
      today.setHours(23, 59, 59, 999);
      if (date > today) {
        return NextResponse.json(
          { success: false, error: "Cannot get statistics for future dates" },
          { status: 400 },
        );
      }
    } else {
      // Default to today
      date = new Date();
    }

    // Convex branch — fetch daily stats from Convex
    if (getDataSource("analytics") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");

        // Build start/end timestamps for the requested date
        const startOfDay = new Date(date);
        startOfDay.setHours(0, 0, 0, 0);
        const endOfDay = new Date(date);
        endOfDay.setHours(23, 59, 59, 999);

        const stats = await convexQuery("analytics/queries:getDailyStats", {
          userId: user.userId,
          startDate: startOfDay.getTime(),
          endDate: endOfDay.getTime(),
        });

        if (stats !== null) {
          return NextResponse.json({
            success: true,
            stats,
            date: date.toISOString().split("T")[0],
          });
        }
      } catch {
        // Fall through to Prisma
      }
    }

    // Get daily statistics
    const stats = await conversationTrackerService.getDailyStats(
      user.userId,
      date,
    );

    scopedLogger.info("Daily statistics retrieved", {
      userId: user.userId,
      date: date.toISOString().split("T")[0],
      totalConversations: stats.totalConversations,
    });

    return NextResponse.json({
      success: true,
      stats,
      date: date.toISOString().split("T")[0], // Return date in YYYY-MM-DD format
    });
  } catch (error) {
    scopedLogger.error("Failed to get daily statistics", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
