/**
 * Single Conversation API
 * GET: Get conversation details with full message history
 * PUT: Update conversation (mark as resolved, escalate, etc.)
 *
 * Supports both user-level (n8n) and org-level WhatsApp conversations.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { whatsappConversationsAdapter } from "@/lib/adapters/whatsapp";
import { withCSRF } from "@/lib/csrf";
import { logger } from "@/lib/logger";
import {
  getEffectiveOwnerId,
  getEffectiveDataOwnerId,
} from "@/lib/utils/organization-data";

export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const conversation = await whatsappConversationsAdapter.findFirst({
      where: {
        id: params.id,
        userId: effectiveUserId,
      },
      include: {
        conversation_messages: {
          orderBy: { timestamp: "asc" },
        },
      },
    });

    if (conversation) {
      // Mark as read
      if (conversation.unreadCount > 0) {
        await prisma.whatsapp_conversations.update({
          where: { id: params.id },
          data: { unreadCount: 0 },
        });
      }
      return NextResponse.json({ conversation });
    }

    // Mark as read
    if ((conversation as any).unreadCount > 0) {
      await whatsappConversationsAdapter.update({
        where: { id: params.id },
        data: { unreadCount: 0 },
      });
    }

    return NextResponse.json(
      { error: "Conversation not found" },
      { status: 404 },
    );
  } catch (error) {
    logger.error("Failed to fetch conversation", error);
    return NextResponse.json(
      { error: "Failed to fetch conversation" },
      { status: 500 },
    );
  }
}

export const PUT = withCSRF(
  async (req: NextRequest, { params }: { params: { id: string } }) => {
    try {
      const session = await auth();
      if (!session?.user?.id) {
        return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
      }

      const body = await req.json();
      const { status, tags } = body;
      const effectiveUserId = await getEffectiveOwnerId(session.user.id);

      const conversation = await whatsappConversationsAdapter.findFirst({
        where: {
          id: params.id,
          userId: effectiveUserId,
        },
      });

      if (conversation) {
        const updated = await prisma.whatsapp_conversations.update({
          where: { id: params.id },
          data: {
            ...(status && { status }),
            ...(tags && { tags }),
          },
        });
        return NextResponse.json({ success: true, conversation: updated });
      }

      const updated = await whatsappConversationsAdapter.update({
        where: { id: params.id },
        data: {
          ...(status && { status }),
          ...(tags && { tags }),
        },
      });

      if (organizationId) {
        const orgConversation =
          await prisma.org_whatsapp_conversations.findFirst({
            where: {
              id: params.id,
              organizationId,
            },
          });

        if (orgConversation) {
          const updated = await prisma.org_whatsapp_conversations.update({
            where: { id: params.id },
            data: {
              ...(status && { status }),
            },
          });
          return NextResponse.json({ success: true, conversation: updated });
        }
      }

      return NextResponse.json(
        { error: "Conversation not found" },
        { status: 404 },
      );
    } catch (error) {
      logger.error("Failed to update conversation", error);
      return NextResponse.json(
        { error: "Failed to update conversation" },
        { status: 500 },
      );
    }
  },
);
