/**
 * Conversation Cleanup Service
 *
 * Deletes WhatsApp conversations older than the org's `dataRetentionDays`
 * setting. Default is 365 days. Designed to run as a daily cron.
 *
 * GDPR compliance: customers' conversation data is automatically purged so
 * orgs don't retain personal data indefinitely.
 *
 * Wire this into a daily cron (e.g. BullMQ repeatable job, Convex action,
 * or external scheduler) by calling `cleanupExpiredConversations()`.
 */

import { logger } from '@/lib/logger';
import { convexQuery, convexMutation } from '@/lib/convex-client';

const DEFAULT_RETENTION_DAYS = 365;
const PER_ORG_FETCH_LIMIT = 1000;

interface OrgRow {
  id: string;
  dataRetentionDays?: number;
}

interface ConvRow {
  _id: string;
  lastMessageAt?: number;
  createdAt?: number;
}

export interface CleanupResult {
  orgsChecked: number;
  conversationsDeleted: number;
  errors: number;
}

export async function cleanupExpiredConversations(): Promise<CleanupResult> {
  let orgsChecked = 0;
  let conversationsDeleted = 0;
  let errors = 0;

  try {
    const { default: prisma } = await import('@/lib/db');
    const orgs = (await prisma.organizations.findMany({
      where: { whatsappWebhookVerified: true },
      select: { id: true, dataRetentionDays: true },
    })) as Array<OrgRow>;

    for (const org of orgs) {
      orgsChecked++;
      const retentionDays = org.dataRetentionDays ?? DEFAULT_RETENTION_DAYS;
      const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000;

      try {
        const convs = await convexQuery<ConvRow[]>(
          'whatsapp/queries:getOrgConversations',
          { organizationId: org.id, limit: PER_ORG_FETCH_LIMIT },
        );
        if (!Array.isArray(convs)) continue;

        const expired = convs.filter((c) => {
          const ts = c.lastMessageAt ?? c.createdAt ?? 0;
          return ts > 0 && ts < cutoffMs;
        });

        for (const conv of expired) {
          try {
            await convexMutation(
              'whatsapp/mutations:deleteOrgConversation',
              { id: conv._id },
            );
            conversationsDeleted++;
          } catch (deleteError) {
            errors++;
            logger.error('[Cleanup] Failed to delete conversation', {
              orgId: org.id,
              conversationId: conv._id,
              error: deleteError,
            });
          }
        }
      } catch (error) {
        errors++;
        logger.error('[Cleanup] Failed for org', { orgId: org.id, error });
      }
    }

    logger.info('[Cleanup] Complete', {
      orgsChecked,
      conversationsDeleted,
      errors,
    });
  } catch (error) {
    logger.error('[Cleanup] Batch failed', { error });
  }

  return { orgsChecked, conversationsDeleted, errors };
}
