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

// Admin-only guard
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/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 client = searchParams.get('client');
  const limit = parseInt(searchParams.get('limit') || '50');
  const offset = parseInt(searchParams.get('offset') || '0');

  let query = supabase
    .from('ad_campaigns')
    .select('*', { count: 'exact' })
    .order('created_at', { ascending: false })
    .range(offset, offset + limit - 1);

  if (publication) query = query.eq('publication_id', publication);
  if (status) query = query.eq('status', status);
  if (client) query = query.ilike('client_name', `%${client}%`);

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

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

// POST /api/adops/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('ad_campaigns')
    .insert({
      campaign_name: body.campaign_name,
      client_name: body.client_name,
      publication_id: body.publication_id,
      placement_zone: body.placement_zone,
      banner_url: body.banner_url,
      destination_url: body.destination_url,
      start_date: body.start_date,
      end_date: body.end_date,
      agreed_rate: body.agreed_rate,
      status: body.status || 'pending_info',
      campaign_type: body.campaign_type || 'banner',
      blackmagic_excluded: body.blackmagic_excluded || false,
      notes: body.notes,
      created_by: user.email,
    })
    .select()
    .single();

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

// PATCH /api/adops/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('ad_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 });
}
