export async function applyRulesToEmail(emailRow, rules) {
  const from = (emailRow.from_addr || '').toLowerCase();
  const subj = (emailRow.subject || '').toLowerCase();
  const body = (emailRow.body_text || '').toLowerCase();
  const thread = (emailRow.thread_key || '').toLowerCase();

  for (const rule of rules) {
    if (!rule.enabled) continue;
    const value = (rule.match_value || '').toLowerCase();
    let hit = false;
    if (rule.match_type === 'from_domain') {
      hit = value && from.includes('@') && from.split('@').pop()?.includes(value.replace(/^@/, ''));
    } else if (rule.match_type === 'from_contains') {
      hit = value && from.includes(value);
    } else if (rule.match_type === 'subject_contains') {
      hit = value && subj.includes(value);
    } else if (rule.match_type === 'body_contains') {
      hit = value && body.includes(value);
    } else if (rule.match_type === 'thread_key') {
      hit = value && thread && thread === value;
    }

    if (hit) {
      return { projectId: rule.project_id, confidence: 0.9, ruleId: rule.id };
    }
  }

  return null;
}
