/**
 * Reorder Review Questions API
 * PUT - Reorder questions within the user's general template
 */

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { reviewQuestionTemplatesAdapter } from "@/lib/adapters/reviews";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

const log = logger.scope("ReviewQuestionsReorderAPI");

const GENERAL_INDUSTRY = "general";

type QuestionRecord = {
  id: string;
  questionEn: string;
  questionAr: string;
  type: string;
  sortOrder: number;
};

type ConvexTemplate = {
  _id: string;
  industry: string;
  questions?: QuestionRecord[];
};

const ReorderSchema = z.object({
  order: z
    .array(
      z.object({
        id: z.string(),
        sortOrder: z.number().int().min(0),
      }),
    )
    .min(1),
});

export async function PUT(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);
    const body = await request.json();
    const parsed = ReorderSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.flatten() },
        { status: 400 },
      );
    }

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexQuery, convexMutation } =
          await import("@/lib/convex-client");

        const templates = await convexQuery(
          "reviews/queries:getQuestionTemplates",
          {
            userId: effectiveUserId,
          },
        );
        const generalTemplate = templates
          ? (templates as ConvexTemplate[]).find(
              (t) => t.industry === GENERAL_INDUSTRY,
            )
          : null;

        if (!generalTemplate) {
          return NextResponse.json(
            { success: false, error: "No question template found" },
            { status: 404 },
          );
        }

        const questions = (generalTemplate.questions ?? []) as QuestionRecord[];
        const orderMap = new Map(
          parsed.data.order.map((o) => [o.id, o.sortOrder]),
        );

        const reordered = questions
          .map((q) => ({
            ...q,
            sortOrder: orderMap.has(q.id)
              ? (orderMap.get(q.id) as number)
              : q.sortOrder,
          }))
          .sort((a, b) => a.sortOrder - b.sortOrder);

        await convexMutation("reviews/mutations:updateQuestionTemplate", {
          userId: effectiveUserId,
          templateId: generalTemplate._id,
          questions: reordered,
        });

        return NextResponse.json({ success: true });
      } catch {
        // Fall through to Prisma
      }
    }

    const template = await reviewQuestionTemplatesAdapter.findUnique({
      where: {
        userId_industry: {
          userId: effectiveUserId,
          industry: GENERAL_INDUSTRY,
        },
      },
    });

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

    const questions = (template.questions ?? []) as QuestionRecord[];
    const orderMap = new Map(parsed.data.order.map((o) => [o.id, o.sortOrder]));

    const reordered = questions
      .map((q) => ({
        ...q,
        sortOrder: orderMap.has(q.id)
          ? (orderMap.get(q.id) as number)
          : q.sortOrder,
      }))
      .sort((a, b) => a.sortOrder - b.sortOrder);

    await reviewQuestionTemplatesAdapter.update({
      where: { id: template.id },
      data: { questions: reordered as unknown },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    log.error("Failed to reorder questions", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
