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

export async function POST(req: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await req.json();
    const { article } = body;

    if (!article || !article.title) {
      return NextResponse.json({ error: 'Article data is required' }, { status: 400 });
    }

    // Fetch all active subscribers
    const { data: subscribers, error: subError } = await supabase
      .from('newsletter_subscribers')
      .select('email')
      .eq('status', 'active');

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

    if (!subscribers || subscribers.length === 0) {
      return NextResponse.json({ success: true, sent: 0, message: 'No active subscribers' });
    }

    const subscriberEmails = subscribers.map((s: { email: string }) => s.email);

    // Call the Supabase Edge Function
    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
    const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

    if (!supabaseUrl || !supabaseAnonKey) {
      return NextResponse.json({ error: 'Supabase configuration missing' }, { status: 500 });
    }

    const edgeFnUrl = `${supabaseUrl}/functions/v1/send-article-notification`;

    const response = await fetch(edgeFnUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${supabaseAnonKey}`,
      },
      body: JSON.stringify({
        article,
        subscribers: subscriberEmails,
      }),
    });

    const result = await response.json();

    if (!response.ok) {
      console.error('Edge function error:', result);
      return NextResponse.json(
        { error: result.error || 'Failed to send notifications' },
        { status: response.status }
      );
    }

    return NextResponse.json({
      success: true,
      sent: result.sent,
      failed: result.failed,
      total: subscriberEmails.length,
    });
  } catch (err: unknown) {
    console.error('notify-article error:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
