/**
 * Onboarding Progress API
 * GET: Retrieve current user's onboarding progress
 * PUT: Update onboarding step completion
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { convexQuery, convexMutation } from "@/lib/convex-client";
import {
  updateProgressSchema,
  calculateOnboardingStatus,
} from "@/lib/types/onboarding.types";
import type { OnboardingProgress } from "@/lib/types/onboarding.types";

// GET /api/onboarding/progress - Get user's onboarding progress
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function GET(_req: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Try to get existing progress from Convex
    let progress = await convexQuery("auth/queries:getOnboardingProgress", {
      userId: session.user.id,
    });

    // If no progress exists, create initial record
    if (!progress) {
      progress = await convexMutation(
        "auth/mutations:createOnboardingProgress",
        {
          userId: session.user.id,
        },
      );
    }

    // Calculate status
    const status = calculateOnboardingStatus(progress as OnboardingProgress);

    return NextResponse.json({
      progress,
      status,
    });
  } catch (error) {
    console.error("Error fetching onboarding progress:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

// PUT /api/onboarding/progress - Update step completion
export async function PUT(req: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await req.json();
    const validationResult = updateProgressSchema.safeParse(body);

    if (!validationResult.success) {
      return NextResponse.json(
        {
          error: "Invalid request data",
          details: validationResult.error.errors,
        },
        { status: 400 },
      );
    }

    const { step, completed = true, data } = validationResult.data;

    // Build update data based on step
    const updateData: Record<string, unknown> = {};

    switch (step) {
      case "welcome":
        updateData.welcomeCompleted = completed;
        break;
      case "whatsapp":
        updateData.whatsappCompleted = completed;
        if (data?.whatsappMethod) {
          updateData.whatsappMethod = data.whatsappMethod;
        }
        break;
      case "voiceAgent":
        updateData.voiceAgentCompleted = completed;
        break;
      case "knowledgeBase":
        updateData.knowledgeBaseCompleted = completed;
        break;
      case "workflows":
        updateData.workflowsCompleted = completed;
        break;
      case "testing":
        updateData.testingCompleted = completed;
        break;
    }

    // Ensure progress record exists first
    let existing = await convexQuery("auth/queries:getOnboardingProgress", {
      userId: session.user.id,
    });

    if (!existing) {
      existing = await convexMutation(
        "auth/mutations:createOnboardingProgress",
        {
          userId: session.user.id,
        },
      );
    }

    // Update in Convex
    const progress = await convexMutation(
      "auth/mutations:updateOnboardingProgress",
      {
        userId: session.user.id,
        ...updateData,
      } as Parameters<typeof convexMutation>[1],
    );

    // Calculate updated status
    const status = calculateOnboardingStatus(progress as OnboardingProgress);

    return NextResponse.json({
      progress,
      status,
    });
  } catch (error) {
    console.error("Error updating onboarding progress:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
