/**
 * Individual Question API — update or delete a single question by its ID
 * PUT    - Update a question's text and type
 * DELETE - Remove a question from the general template
 *
 * Note: [templateId] is reused as the route param name but acts as questionId here.
 */

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("ReviewQuestionAPI");

const GENERAL_INDUSTRY = "general";

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

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

async function getGeneralTemplate(userId: string) {
  return reviewQuestionTemplatesAdapter.findUnique({
    where: { userId_industry: { userId, industry: GENERAL_INDUSTRY } },
  });
}

const UpdateQuestionSchema = z.object({
  questionEn: z.string().min(1).max(500),
  questionAr: z.string().min(0).max(500).default(""),
  type: z.enum(["rating", "text", "yesno"]).default("text"),
});

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ templateId: string }> },
) {
  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 { templateId: questionId } = await params;
    const body = await request.json();
    const parsed = UpdateQuestionSchema.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 idx = questions.findIndex((q) => q.id === questionId);
        if (idx === -1) {
          return NextResponse.json(
            { success: false, error: "Question not found" },
            { status: 404 },
          );
        }

        questions[idx] = {
          ...questions[idx],
          questionEn: parsed.data.questionEn,
          questionAr: parsed.data.questionAr,
          type: parsed.data.type,
        };

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

        return NextResponse.json({
          success: true,
          question: { ...questions[idx], industry: GENERAL_INDUSTRY },
        });
      } catch {
        // Fall through to Prisma
      }
    }

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

    const questions = (template.questions ?? []) as QuestionRecord[];
    const idx = questions.findIndex((q) => q.id === questionId);
    if (idx === -1) {
      return NextResponse.json(
        { success: false, error: "Question not found" },
        { status: 404 },
      );
    }

    questions[idx] = {
      ...questions[idx],
      questionEn: parsed.data.questionEn,
      questionAr: parsed.data.questionAr,
      type: parsed.data.type,
    };

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

    return NextResponse.json({
      success: true,
      question: { ...questions[idx], industry: GENERAL_INDUSTRY },
    });
  } catch (error) {
    log.error("Failed to update question", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ templateId: string }> },
) {
  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 { templateId: questionId } = await params;

    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 filtered = questions.filter((q) => q.id !== questionId);

        if (filtered.length === questions.length) {
          return NextResponse.json(
            { success: false, error: "Question not found" },
            { status: 404 },
          );
        }

        // Re-assign sortOrder after deletion
        const reordered = filtered.map((q, i) => ({ ...q, sortOrder: i }));

        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 getGeneralTemplate(effectiveUserId);
    if (!template) {
      return NextResponse.json(
        { success: false, error: "No question template found" },
        { status: 404 },
      );
    }

    const questions = (template.questions ?? []) as QuestionRecord[];
    const filtered = questions.filter((q) => q.id !== questionId);

    if (filtered.length === questions.length) {
      return NextResponse.json(
        { success: false, error: "Question not found" },
        { status: 404 },
      );
    }

    // Re-assign sortOrder after deletion
    const reordered = filtered.map((q, i) => ({ ...q, sortOrder: i }));

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

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