import { ContactActivityType } from '@prisma/client';
import { prisma } from '../config/database';
import { logger } from './logger';

interface RecordActivityParams {
  userId?: string;
  email?: string;
  contactId?: string;
  activityType: ContactActivityType;
  title: string;
  description?: string;
  metadata?: Record<string, unknown>;
}

/**
 * Fire-and-forget CRM activity recorder.
 * Resolves a Contact by userId or email, then writes a ContactActivity row.
 * Skips silently if no matching Contact is found (anonymous users).
 */
export async function recordCrmActivity(params: RecordActivityParams): Promise<void> {
  try {
    let contactId = params.contactId;

    if (!contactId) {
      const conditions: Record<string, unknown>[] = [];
      if (params.userId) conditions.push({ userId: params.userId });
      if (params.email) conditions.push({ email: params.email });

      if (conditions.length === 0) return;

      const contact = await prisma.contact.findFirst({
        where: {
          mergedIntoId: null,
          OR: conditions,
        },
        select: { id: true },
      });

      if (!contact) return;
      contactId = contact.id;
    }

    await prisma.contactActivity.create({
      data: {
        contactId,
        type: params.activityType,
        title: params.title,
        description: params.description,
        metadata: params.metadata as unknown as import('@prisma/client').Prisma.InputJsonValue,
      },
    });
  } catch (err) {
    logger.error('Failed to record CRM activity', { error: err instanceof Error ? err.message : String(err), params: { activityType: params.activityType } });
  }
}
