/**
 * WhatsApp Conversations Service
 *
 * Lists and manages WhatsApp conversation threads for the dashboard.
 */

import { prisma } from '@/lib/db';
import type { ConversationListQueryInput, ConversationLogInput } from '@/lib/validators/whatsapp-ai.validator';

export interface ConversationSummary {
  id: string;
  customerPhone: string;
  customerName: string | null;
  lastMessage: string | null;
  lastMessageAt: Date | null;
  status: string;
  language: string | null;
  messageCount: number;
}

/** 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 listConversations(params: ConversationListQueryInput) {
  const { organizationId, language, status, limit, offset } = params;

  // Read from org_whatsapp_conversations — the org-scoped table that the
  // unified Twilio + Meta webhooks write to. (The legacy whatsapp_conversations
  // table from the old n8n flow is not used by the dashboard inbox.)
  const where: Record<string, unknown> = { organizationId };
  if (status) where.status = status;
  if (language) where.language = language;

  try {
    const [conversations, total] = await Promise.all([
      prisma.org_whatsapp_conversations.findMany({
        where,
        orderBy: { updatedAt: 'desc' },
        take: limit,
        skip: offset,
      }),
      prisma.org_whatsapp_conversations.count({ where }),
    ]);

    // For each conversation, fetch the last 5 messages so the inbox can
    // preview the most recent line and the user can scroll through context
    // without an extra round-trip.
    const enriched = await Promise.all(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (conversations as any[]).map(async (c) => {
        const conversationId = c.id ?? c._id;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let messages: any[] = [];
        try {
          const rows = await prisma.org_whatsapp_messages.findMany({
            where: { conversationId },
            orderBy: { timestamp: 'asc' },
            take: 50,
          });
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          messages = (rows as any[]).map((m) => ({
            id: m.id ?? m._id,
            role: m.role,
            content: m.content,
            language: m.language ?? c.language ?? 'en',
            intent: m.intent ?? null,
            toolsUsed: Array.isArray(m.toolsUsed) ? m.toolsUsed : [],
            metadata: m.metadata ?? null,
            timestamp: toDate(m.timestamp) ?? new Date(),
          }));
        } catch {
          // Non-fatal — leave messages empty
        }

        // Match the WhatsAppInbox component's Conversation interface
        // exactly: userPhone, userName, messages[], humanControlled flags,
        // createdAt, lastMessageAt as Date.
        return {
          id: conversationId,
          organizationId: c.organizationId ?? organizationId,
          userPhone: c.userPhone ?? '',
          userName: c.userName ?? null,
          language: c.language ?? 'en',
          status: c.status ?? 'active',
          lastMessageAt: toDate(c.lastMessageAt) ?? toDate(c.updatedAt),
          messageCount: c.messageCount ?? messages.length,
          createdAt: toDate(c.createdAt) ?? new Date(),
          messages,
          humanControlled: !!c.humanControlled,
          humanControlledAt: c.humanControlledAt
            ? toDate(c.humanControlledAt)?.toISOString() ?? null
            : null,
          humanControlledBy: c.humanControlledBy ?? null,
        };
      }),
    );

    return {
      conversations: enriched,
      total: typeof total === 'number' ? total : enriched.length,
    };
  } catch (error) {
    // Table may not exist yet or query failed — return empty so the inbox
    // shows "no conversations" instead of crashing the page.
    // eslint-disable-next-line no-console
    console.error('[listConversations] failed', error);
    return { conversations: [], total: 0 };
  }
}

/**
 * Log a WhatsApp conversation and its messages to the database.
 * Returns the conversation ID.
 */
export async function logConversation(input: ConversationLogInput): Promise<string> {
  try {
    // Upsert conversation record
    const conversation = await prisma.whatsapp_conversations.upsert({
      where: {
        organizationId_customerPhone: {
          organizationId: input.organizationId,
          customerPhone: input.userPhone,
        },
      },
      update: {
        customerName: input.userName ?? undefined,
        language: input.language,
        lastMessage: input.messages[input.messages.length - 1]?.content ?? null,
        messageCount: { increment: input.messages.length },
        updatedAt: new Date(),
      },
      create: {
        organizationId: input.organizationId,
        customerPhone: input.userPhone,
        customerName: input.userName ?? null,
        language: input.language ?? 'en',
        status: 'active',
        lastMessage: input.messages[input.messages.length - 1]?.content ?? null,
        messageCount: input.messages.length,
      },
    });

    // Log individual messages
    for (const msg of input.messages) {
      await prisma.whatsapp_messages.create({
        data: {
          conversationId: conversation.id,
          role: msg.role,
          content: msg.content,
          language: msg.language ?? input.language ?? 'en',
          intent: msg.intent ?? null,
          metadata: msg.metadata ? JSON.stringify(msg.metadata) : null,
        },
      });
    }

    return conversation.id;
  } catch {
    // If tables don't exist, return a placeholder
    return `pending-${Date.now()}`;
  }
}
