import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';

// POST /api/email/inbound-reply — called by Kerio when reply arrives
export async function POST(request: NextRequest) {
  const supabase = await createClient();
  const body = await request.json();

  const fromEmail: string = body.from ?? '';
  const replyBody: string = body.body ?? body.text ?? '';
  const sendingDomain: string = body.to_domain ?? body.domain ?? '';

  if (!fromEmail) return NextResponse.json({ ok: false, error: 'No from address' }, { status: 400 });

  // Identify site from sending domain
  const { data: domainRecord } = await supabase
    .from('rmp_email_sending_domains')
    .select('site')
    .eq('domain', sendingDomain)
    .single();

  const site = domainRecord?.site ?? 'avbeat';

  // Load active keywords
  const { data: keywords } = await supabase
    .from('rmp_suppression_keywords')
    .select('keyword, keyword_type')
    .eq('active', true);

  const bodyLower = replyBody.toLowerCase();
  let matchedKeyword: { keyword: string; keyword_type: string } | null = null;

  for (const kw of (keywords ?? [])) {
    if (bodyLower.includes(kw.keyword.toLowerCase())) {
      matchedKeyword = kw;
      break;
    }
  }

  if (matchedKeyword) {
    const suppression_type = matchedKeyword.keyword_type === 'hostile' ? 'hostile_reply' : 'unsubscribe';

    // Upsert suppression
    await supabase.from('rmp_email_suppressions').upsert({
      site,
      email: fromEmail.toLowerCase().trim(),
      suppression_type,
      source: 'reply_inbound',
      reply_text: replyBody.slice(0, 500),
      sending_domain: sendingDomain,
      suppressed_by: 'system',
    }, { onConflict: 'site,email' });

    // Notify admin
    const notifyEmail = process.env.NOTIFY_EMAIL;
    if (notifyEmail) {
      try {
        await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/marketplace/send-email`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            to: notifyEmail,
            subject: `RMP Email ${suppression_type}: ${fromEmail}`,
            text: `${fromEmail} replied with: ${replyBody.slice(0, 200)}`,
          }),
        });
      } catch {}
    }

    return NextResponse.json({ ok: true, action: 'suppressed', type: suppression_type });
  }

  // No keyword match — route to normal inbox (no action needed)
  return NextResponse.json({ ok: true, action: 'routed' });
}
