import { logger } from '../../utils/logger.js';
import { db } from '../../config/database.js';
import { contacts } from '../../db/schema.js';
import { eq } from 'drizzle-orm';
import { jmapRequest } from './client.js';

/**
 * Discover potential contacts from JMAP (no DB storage)
 * Returns list of unique senders
 */
export const discoverContactsFromJMAP = async (jmapConfig, emailAccountId, searchTerm = '', limit = 50) => {
  try {
    logger.info(`Objavovanie kontaktov z JMAP (hľadanie: "${searchTerm}")`);

    // Query emails, sorted by date
    const queryResponse = await jmapRequest(jmapConfig, [
      [
        'Email/query',
        {
          accountId: jmapConfig.accountId,
          filter: searchTerm
            ? {
                operator: 'OR',
                conditions: [{ from: searchTerm }, { subject: searchTerm }],
              }
            : undefined,
          sort: [{ property: 'receivedAt', isAscending: false }],
          limit: 200, // Fetch more to get diverse senders
        },
        'query1',
      ],
    ]);

    const emailIds = queryResponse.methodResponses?.[0]?.[1]?.ids;

    if (!emailIds || emailIds.length === 0) {
      return [];
    }

    // Fetch email metadata (no bodies)
    const getResponse = await jmapRequest(jmapConfig, [
      [
        'Email/get',
        {
          accountId: jmapConfig.accountId,
          ids: emailIds,
          properties: ['from', 'subject', 'receivedAt', 'preview'],
        },
        'get1',
      ],
    ]);

    const emailsList = getResponse.methodResponses[0][1].list;

    // Get existing contacts for this email account
    const existingContacts = await db
      .select()
      .from(contacts)
      .where(eq(contacts.emailAccountId, emailAccountId));

    const contactEmailsSet = new Set(existingContacts.map((c) => c.email.toLowerCase()));

    // Group by sender (unique senders)
    const sendersMap = new Map();
    const myEmail = jmapConfig.username.toLowerCase();

    emailsList.forEach((email) => {
      const fromEmail = email.from?.[0]?.email;

      if (!fromEmail || fromEmail.toLowerCase() === myEmail) {
        return; // Skip my own emails
      }

      // Keep only the most recent email from each sender
      if (!sendersMap.has(fromEmail)) {
        sendersMap.set(fromEmail, {
          email: fromEmail,
          name: email.from?.[0]?.name || fromEmail.split('@')[0],
          latestSubject: email.subject || '(Bez predmetu)',
          latestDate: email.receivedAt,
          snippet: email.preview || '',
          isContact: contactEmailsSet.has(fromEmail.toLowerCase()),
        });
      }
    });

    const senders = Array.from(sendersMap.values())
      .sort((a, b) => new Date(b.latestDate) - new Date(a.latestDate))
      .slice(0, limit);

    logger.success(`Nájdených ${senders.length} unikátnych odosielateľov`);
    return senders;
  } catch (error) {
    logger.error('Nepodarilo sa objaviť kontakty z JMAP', error);
    throw error;
  }
};
