import { NextRequest, NextResponse } from 'next/server';
import { pollImapInbox, processInboundEmail } from '@/lib/adops/imapMonitor';
import { retryPendingInvoices } from '@/lib/adops/adOpsInvoiceService';
import { createClient } from '@/lib/supabase/server';

async function requireAdmin(request: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return null;
  const { data: profile } = await supabase
    .from('user_profiles')
    .select('role')
    .eq('id', user.id)
    .single();
  if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
  return user;
}

// POST /api/adops/poll — trigger IMAP poll (called by cron or manually)
export async function POST(request: NextRequest) {
  // Allow cron secret or admin auth
  const cronSecret = request.headers.get('x-cron-secret');
  const isValidCron = cronSecret && cronSecret === process.env.CRON_SECRET;

  if (!isValidCron) {
    const user = await requireAdmin(request);
    if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

  const body = await request.json().catch(() => ({}));
  const action = body.action || 'poll';

  if (action === 'retry_invoices') {
    await retryPendingInvoices();
    return NextResponse.json({ success: true, action: 'retry_invoices' });
  }

  // Poll IMAP
  const emails = await pollImapInbox();
  let processed = 0;
  let errors = 0;

  for (const email of emails) {
    try {
      await processInboundEmail(email);
      processed++;
    } catch (err: any) {
      console.error('[AdOps Poll] Error processing email:', err.message);
      errors++;
    }
  }

  return NextResponse.json({
    success: true,
    found: emails.length,
    processed,
    errors,
    timestamp: new Date().toISOString(),
  });
}

// GET /api/adops/poll — get inbox log
export async function GET(request: NextRequest) {
  const user = await requireAdmin(request);
  if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const supabase = await createClient();
  const { data, error } = await supabase
    .from('adops_inbox_log')
    .select('*')
    .order('received_at', { ascending: false })
    .limit(50);

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ logs: data });
}
