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

import type {
  ProjectAnalyticsChatMatch,
  ProjectAnalyticsDateRange,
  ProjectAnalyticsMessageIndexRow,
  ProjectAnalyticsVisitorRow,
} from '@/lib/project-analytics/project-analytics-types';

/** Characters of context kept either side of a match in the chat list. */
const SNIPPET_PADDING = 60;

/** Upper bound on rendered chat matches, so a one-letter query cannot hang the page. */
export const MAX_CHAT_MATCHES = 100;

export const EMPTY_DATE_RANGE: ProjectAnalyticsDateRange = { from: null, to: null };

export function isDateRangeActive(range: ProjectAnalyticsDateRange): boolean {
  return Boolean(range.from || range.to);
}

/**
 * Turn a `YYYY-MM-DD` range bound into a local-time day boundary.
 *
 * The components are read out and passed to the Date constructor rather than
 * letting it parse the string: `new Date('2026-05-01')` is parsed as UTC
 * midnight, and calling setHours on that mixes UTC and local. East of UTC the
 * result happens to be right; west of UTC it lands a whole day early. The
 * picker hands us the day the user clicked, so the boundary has to be that
 * day in their own timezone.
 */
function localDayBoundary(value: string, edge: 'start' | 'end'): number | null {
  const parts = /^(\d{4})-(\d{2})-(\d{2})/.exec(value);
  const date = parts
    ? new Date(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]))
    : new Date(value);

  if (Number.isNaN(date.getTime())) return null;

  if (edge === 'start') date.setHours(0, 0, 0, 0);
  else date.setHours(23, 59, 59, 999);
  return date.getTime();
}

/**
 * Whether an ISO timestamp falls inside a range.
 *
 * Both ends are inclusive by whole local day, so picking the same date for
 * from and to matches everything that happened on it — which is what someone
 * selecting a single day means.
 */
export function isWithinDateRange(
  isoTimestamp: string | null,
  range: ProjectAnalyticsDateRange,
): boolean {
  if (!isDateRangeActive(range)) return true;
  if (!isoTimestamp) return false;

  const value = new Date(isoTimestamp).getTime();
  if (Number.isNaN(value)) return false;

  if (range.from) {
    const from = localDayBoundary(range.from, 'start');
    if (from !== null && value < from) return false;
  }
  if (range.to) {
    const to = localDayBoundary(range.to, 'end');
    if (to !== null && value > to) return false;
  }
  return true;
}

/** The visitor-column fields the search box has always matched. */
export function visitorMatchesQuery(
  visitor: ProjectAnalyticsVisitorRow,
  loweredQuery: string,
): boolean {
  if (!loweredQuery) return true;
  const loc = visitor.location;
  return [
    visitor.name ?? '',
    visitor.email ?? '',
    visitor.phone ?? '',
    loc?.country ?? '',
    loc?.state ?? '',
    loc?.city ?? '',
  ].some((value) => value.toLowerCase().includes(loweredQuery));
}

export function filterVisitors(
  visitors: ProjectAnalyticsVisitorRow[],
  args: {
    query: string;
    firstMessageRange: ProjectAnalyticsDateRange;
    lastMessageRange: ProjectAnalyticsDateRange;
  },
): ProjectAnalyticsVisitorRow[] {
  const q = args.query.trim().toLowerCase();
  return visitors.filter(
    (visitor) =>
      visitorMatchesQuery(visitor, q) &&
      isWithinDateRange(visitor.firstMessageAt, args.firstMessageRange) &&
      isWithinDateRange(visitor.lastMessageAt, args.lastMessageRange),
  );
}

function buildSnippet(content: string, index: number, queryLength: number) {
  const start = Math.max(0, index - SNIPPET_PADDING);
  const end = Math.min(content.length, index + queryLength + SNIPPET_PADDING);
  const prefix = start > 0 ? '…' : '';
  const suffix = end < content.length ? '…' : '';
  const snippet = `${prefix}${content.slice(start, end)}${suffix}`;
  const matchStart = prefix.length + (index - start);
  return { snippet, matchStart, matchEnd: matchStart + queryLength };
}

/**
 * Messages whose text contains the query, newest first.
 *
 * Only the first occurrence in a message is surfaced — a chat list is for
 * finding the conversation, not for counting every hit inside it.
 */
export function buildChatMatches(
  messages: ProjectAnalyticsMessageIndexRow[],
  query: string,
  args?: {
    firstMessageRange?: ProjectAnalyticsDateRange;
    lastMessageRange?: ProjectAnalyticsDateRange;
    visitorIdAllowList?: Set<string> | null;
  },
): ProjectAnalyticsChatMatch[] {
  const q = query.trim().toLowerCase();
  if (!q) return [];

  const allowList = args?.visitorIdAllowList ?? null;
  const out: ProjectAnalyticsChatMatch[] = [];

  for (const message of messages) {
    if (out.length >= MAX_CHAT_MATCHES) break;
    if (allowList && (!message.visitorContactId || !allowList.has(message.visitorContactId))) {
      continue;
    }

    const index = message.content.toLowerCase().indexOf(q);
    if (index === -1) continue;

    out.push({ ...message, ...buildSnippet(message.content, index, q.length) });
  }

  return out;
}
