import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth } from "@/lib/auth";
import { existsSync } from "fs";
import { join } from "path";

/**
 * GET /api/learn/tts?moduleId=xxx
 * Returns module text content and whether audio is cached on disk.
 * The client uses Web Speech API as the baseline — no server-side TTS yet.
 */
export async function GET(request: NextRequest) {
  const jwt = await requireAuth(request);
  if (!jwt) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const { searchParams } = new URL(request.url);
    const moduleId = searchParams.get("moduleId");

    if (!moduleId) {
      return NextResponse.json(
        { error: "moduleId query parameter is required" },
        { status: 400 }
      );
    }

    const module = await prisma.learnModule.findUnique({
      where: { id: moduleId },
      select: { id: true, content: true, audioPath: true },
    });

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

    let hasAudio = false;
    if (module.audioPath) {
      const fullPath = join(process.cwd(), "public", module.audioPath);
      hasAudio = existsSync(fullPath);
    }

    return NextResponse.json({
      moduleId: module.id,
      text: module.content ?? "",
      hasAudio,
    });
  } catch (error) {
    console.error("GET /api/learn/tts error:", error);
    return NextResponse.json(
      { error: "Failed to retrieve TTS data" },
      { status: 500 }
    );
  }
}

/**
 * POST /api/learn/tts
 * Body: { moduleId }
 * 1) Verifies auth, 2) Finds the LearnModule, 3) Checks if audio is cached on disk,
 * 4) Returns text content so the client can use Web Speech API (SpeechSynthesis).
 * Server-side TTS generation can be added later.
 */
export async function POST(request: Request) {
  const jwt = await requireAuth(request);
  if (!jwt) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { moduleId } = body;

    if (!moduleId) {
      return NextResponse.json(
        { error: "moduleId is required" },
        { status: 400 }
      );
    }

    const module = await prisma.learnModule.findUnique({
      where: { id: moduleId },
      select: { id: true, content: true, audioPath: true },
    });

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

    const text = module.content ?? "";

    // Check if audio is already cached on disk
    if (module.audioPath) {
      const fullPath = join(process.cwd(), "public", module.audioPath);
      if (existsSync(fullPath)) {
        return NextResponse.json({
          audioUrl: module.audioPath.startsWith("/")
            ? module.audioPath
            : `/audio/${module.audioPath}`,
          cached: true,
          text,
        });
      }
    }

    // No cached audio — return text for client-side Web Speech API
    // If we don't have an audioPath yet, set a pending marker so future
    // server-side TTS knows this module is queued.
    if (!module.audioPath) {
      await prisma.learnModule.update({
        where: { id: module.id },
        data: { audioPath: "__pending__" },
      });
    }

    return NextResponse.json({
      text,
      moduleId: module.id,
      ttsUrl: null,
      cached: false,
      message:
        "Audio not yet generated. Use Web Speech API (SpeechSynthesis) on the client to speak this text.",
    });
  } catch (error) {
    console.error("POST /api/learn/tts error:", error);
    return NextResponse.json(
      { error: "Failed to process TTS request" },
      { status: 500 }
    );
  }
}
