/*
*  author: Yagnik Poshiya
*  organization: Webbrains Technologies Private Limited
*/

import { listProjectConnectedAgentsCatalogForCurrentUser } from '@/lib/projects/list-project-connected-agents-catalog';
import type { ProjectAnalyticsMessagesApiResult } from '@/lib/project-analytics/project-analytics-types';
import { getSupabaseServerClient } from '@/lib/supabase/server';

/**
 * How many messages are pulled into the browser for searching.
 *
 * Search runs in the browser, not on the server: a request per keystroke is
 * slow enough to feel broken, and the visitor table is already searched
 * in-memory. The whole message corpus is small (~300 chars average), so the
 * index is a single background fetch rather than a query per search.
 *
 * The cap keeps that honest as data grows. When it is hit the UI says so,
 * rather than quietly searching a subset.
 */
export const ANALYTICS_MESSAGE_INDEX_LIMIT = 5000;

type ConversationRow = { id: string; visitor_contact_id: string | null };
type MessageRow = {
  id: string;
  conversation_id: string;
  role: string;
  content: string | null;
  created_at: string | null;
};
type VisitorRow = { id: string; name: string | null; email: string | null };

export async function listProjectAnalyticsMessagesForCurrentUser(
  projectId: string,
  projectAgentId: string,
): Promise<ProjectAnalyticsMessagesApiResult> {
  const pid = String(projectId ?? '').trim();
  const paId = String(projectAgentId ?? '').trim();
  if (!pid) return { ok: false, message: 'Missing project id.', code: 'NOT_FOUND' };
  if (!paId) return { ok: false, message: 'Missing project agent id.', code: 'BAD_REQUEST' };

  const catalog = await listProjectConnectedAgentsCatalogForCurrentUser(pid);
  if (!catalog.ok) return catalog;

  const selectedAgent = catalog.agents.find((agent) => agent.projectAgentId === paId);
  if (!selectedAgent) {
    return { ok: false, message: 'Connected agent not found in this project.', code: 'NOT_FOUND' };
  }

  const supabase = await getSupabaseServerClient();

  const { data: conversationRows, error: conversationError } = await supabase
    .from('conversations')
    .select('id, visitor_contact_id')
    .eq('project_agent_id', paId);

  if (conversationError) return { ok: false, message: conversationError.message };

  const conversations = (conversationRows ?? []) as ConversationRow[];
  if (conversations.length === 0) {
    return { ok: true, messages: [], truncated: false, limit: ANALYTICS_MESSAGE_INDEX_LIMIT };
  }

  const conversationIds = conversations.map((c) => c.id);
  const visitorIdByConversation = new Map(
    conversations.map((c) => [c.id, c.visitor_contact_id] as const),
  );

  // Newest first, so hitting the cap drops the oldest messages rather than a
  // random slice.
  const { data: messageRows, error: messageError } = await supabase
    .from('messages')
    .select('id, conversation_id, role, content, created_at')
    .in('conversation_id', conversationIds)
    .in('role', ['visitor', 'agent'])
    .order('created_at', { ascending: false })
    .limit(ANALYTICS_MESSAGE_INDEX_LIMIT + 1);

  if (messageError) return { ok: false, message: messageError.message };

  const rows = (messageRows ?? []) as MessageRow[];
  const truncated = rows.length > ANALYTICS_MESSAGE_INDEX_LIMIT;
  const capped = truncated ? rows.slice(0, ANALYTICS_MESSAGE_INDEX_LIMIT) : rows;

  const visitorIds = [
    ...new Set(
      capped
        .map((m) => visitorIdByConversation.get(m.conversation_id))
        .filter((id): id is string => Boolean(id)),
    ),
  ];

  const visitorById = new Map<string, VisitorRow>();
  if (visitorIds.length > 0) {
    const { data: visitorRows, error: visitorError } = await supabase
      .from('visitor_contacts')
      .select('id, name, email')
      .in('id', visitorIds);

    if (visitorError) return { ok: false, message: visitorError.message };
    for (const row of (visitorRows ?? []) as VisitorRow[]) visitorById.set(row.id, row);
  }

  const messages = capped
    .filter((m) => (m.content ?? '').trim().length > 0)
    .map((m) => {
      const visitorId = visitorIdByConversation.get(m.conversation_id) ?? null;
      const visitor = visitorId ? visitorById.get(visitorId) : undefined;
      return {
        id: m.id,
        conversationId: m.conversation_id,
        visitorContactId: visitorId,
        visitorName: visitor?.name ?? null,
        visitorEmail: visitor?.email ?? null,
        role: m.role === 'agent' ? ('agent' as const) : ('visitor' as const),
        content: m.content ?? '',
        createdAt: m.created_at,
      };
    });

  return { ok: true, messages, truncated, limit: ANALYTICS_MESSAGE_INDEX_LIMIT };
}
