import { NextRequest, NextResponse } from 'next/server';
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;
}

// GET /api/adops/email-campaigns
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 { searchParams } = new URL(request.url);
  const publication = searchParams.get('publication');
  const status = searchParams.get('status');
  const isNewsletter = searchParams.get('newsletter');

  let query = supabase
    .from('adops_email_campaigns')
    .select('*, email_lists(list_name, subscriber_count)')
    .order('created_at', { ascending: false });

  if (publication) query = query.eq('publication_id', publication);
  if (status) query = query.eq('status', status);
  if (isNewsletter !== null) query = query.eq('is_newsletter', isNewsletter === 'true');

  const { data, error } = await query;
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  return NextResponse.json({ campaigns: data });
}

// POST /api/adops/email-campaigns
export async function POST(request: NextRequest) {
  const user = await requireAdmin(request);
  if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const supabase = await createClient();
  const body = await request.json();

  const { data, error } = await supabase
    .from('adops_email_campaigns')
    .insert({
      campaign_name: body.campaign_name,
      client_name: body.client_name,
      publication_id: body.publication_id,
      list_id: body.list_id,
      subject: body.subject,
      from_name: body.from_name,
      from_email: body.from_email,
      reply_to: body.reply_to,
      html_content: body.html_content,
      send_date: body.send_date,
      send_time_et: body.send_time_et || '11:00',
      status: 'draft',
      agreed_rate: body.agreed_rate,
      is_newsletter: body.is_newsletter || false,
    })
    .select()
    .single();

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

// PATCH /api/adops/email-campaigns
export async function PATCH(request: NextRequest) {
  const user = await requireAdmin(request);
  if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const supabase = await createClient();
  const body = await request.json();
  const { id, ...updates } = body;

  if (!id) return NextResponse.json({ error: 'Campaign ID required' }, { status: 400 });

  const { data, error } = await supabase
    .from('adops_email_campaigns')
    .update({ ...updates, updated_at: new Date().toISOString() })
    .eq('id', id)
    .select()
    .single();

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