/**
 * Dashboard WhatsApp Conversation Detail API
 *
 * GET /api/dashboard/whatsapp-conversations/[id]
 * Returns a single conversation with its latest messages from
 * org_whatsapp_messages — used by the conversation detail modal
 * auto-poll loop to refresh messages every 5 seconds.
 *
 * The response shape matches what ConversationDetailModal expects:
 *   { success: true, data: { id, messages, humanControlled, ... } }
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveDataOwnerId } from "@/lib/utils/organization-data";
import { logger } from "@/lib/logger";

export const dynamic = "force-dynamic";

/** Coerce a Date | epoch ms | ISO string into a Date (or null). */
function toDate(raw: unknown): Date | null {
  if (raw instanceof Date) return raw;
  if (typeof raw === "number") return new Date(raw);
  if (typeof raw === "string") return new Date(raw);
  return null;
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id } = await params;

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

    const { organizationId } = await getEffectiveDataOwnerId(user.userId);
    if (!organizationId) {
      return NextResponse.json(
        { success: false, error: "No organization" },
        { status: 403 },
      );
    }

    // Fetch conversation — must belong to the caller's organization.
    const conversation = await prisma.org_whatsapp_conversations.findUnique({
      where: { id },
    });

    if (!conversation) {
      return NextResponse.json(
        { success: false, error: "Conversation not found" },
        { status: 404 },
      );
    }

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const conv = conversation as any;

    if (conv.organizationId !== organizationId) {
      return NextResponse.json(
        { success: false, error: "Access denied" },
        { status: 403 },
      );
    }

    // Fetch messages ordered ascending so the modal can append new ones
    // naturally at the bottom.
    const rows = await prisma.org_whatsapp_messages.findMany({
      where: { conversationId: id },
      orderBy: { timestamp: "asc" },
      take: 200,
    });

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const messages = (rows as any[]).map((m) => ({
      id: m.id ?? m._id,
      role: m.role,
      content: m.content,
      language: m.language ?? conv.language ?? "en",
      intent: m.intent ?? null,
      toolsUsed: Array.isArray(m.toolsUsed) ? m.toolsUsed : [],
      metadata: m.metadata ?? null,
      timestamp: toDate(m.timestamp) ?? new Date(),
    }));

    return NextResponse.json({
      success: true,
      data: {
        id: conv.id ?? conv._id,
        organizationId: conv.organizationId,
        userPhone: conv.userPhone ?? "",
        userName: conv.userName ?? null,
        language: conv.language ?? "en",
        status: conv.status ?? "active",
        lastMessageAt: toDate(conv.lastMessageAt) ?? toDate(conv.updatedAt),
        messageCount: conv.messageCount ?? messages.length,
        createdAt: toDate(conv.createdAt) ?? new Date(),
        messages,
        humanControlled: !!conv.humanControlled,
        humanControlledAt: conv.humanControlledAt
          ? toDate(conv.humanControlledAt)?.toISOString() ?? null
          : null,
        humanControlledBy: conv.humanControlledBy ?? null,
      },
    });
  } catch (error) {
    logger.error("Dashboard conversation detail error", {
      error: error instanceof Error ? error.message : String(error),
    });
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
