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';

/**
 * Search emails using JMAP full-text search
 * Searches in: from, to, subject, and email body
 * Returns list of unique senders grouped by email address
 */
export const searchEmailsJMAP = async (jmapConfig, emailAccountId, query, limit = 50, offset = 0) => {
  try {
    logger.info(`Vyhľadávanie emailov v JMAP (dopyt: "${query}", limit: ${limit}, offset: ${offset})`);

    if (!query || query.trim().length < 1) {
      return [];
    }

    // Use JMAP search with wildcards for substring matching
    // Add wildcards (*) to enable partial matching: "ander" -> "*ander*"
    const wildcardQuery = query.includes('*') ? query : `*${query}*`;

    let queryResponse;

    try {
      // Try with 'text' filter first (full-text search if supported)
      queryResponse = await jmapRequest(jmapConfig, [
        [
          'Email/query',
          {
            accountId: jmapConfig.accountId,
            filter: {
              text: wildcardQuery, // Full-text search with wildcards
            },
            sort: [{ property: 'receivedAt', isAscending: false }],
            position: offset,
            limit: 200,
          },
          'query1',
        ],
      ]);
    } catch (textFilterError) {
      // If 'text' filter fails, fall back to OR conditions with wildcards
      logger.warn('Textový filter zlyhal, prepínam na OR podmienky', textFilterError);
      queryResponse = await jmapRequest(jmapConfig, [
        [
          'Email/query',
          {
            accountId: jmapConfig.accountId,
            filter: {
              operator: 'OR',
              conditions: [
                { from: wildcardQuery },
                { to: wildcardQuery },
                { subject: wildcardQuery },
              ],
            },
            sort: [{ property: 'receivedAt', isAscending: false }],
            position: offset,
            limit: 200,
          },
          'query1',
        ],
      ]);
    }

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

    if (!emailIds || emailIds.length === 0) {
      logger.info('Nenašli sa žiadne emaily zodpovedajúce dopytu');
      return [];
    }

    logger.info(`Nájdených ${emailIds.length} emailov zodpovedajúcich dopytu`);

    // Fetch email metadata
    const getResponse = await jmapRequest(jmapConfig, [
      [
        'Email/get',
        {
          accountId: jmapConfig.accountId,
          ids: emailIds,
          properties: ['from', 'to', '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()),
        });
      }
    });

    // Convert to array, sort by date, and apply limit
    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 zodpovedajúcich dopytu`);
    return senders;
  } catch (error) {
    logger.error('Nepodarilo sa vyhľadať emaily v JMAP', error);
    throw error;
  }
};
