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

// GET: fetch all articles (both imported and native)
export async function GET(req: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const source = searchParams.get('source') || 'all';
  const status = searchParams.get('status') || 'all';
  const search = searchParams.get('search') || '';

  // Auto-publish any scheduled articles that are due
  await supabase.rpc('publish_scheduled_articles');

  let imported: any[] = [];
  let native: any[] = [];

  if (source === 'all' || source === 'imported') {
    let q = supabase
      .from('wp_imported_posts')
      .select('id, title, author_name, category, featured_image, featured_image_alt, wp_published_at, imported_at, status, wp_slug, scheduled_at, submitted_for_review_at')
      .order('imported_at', { ascending: false });
    if (status !== 'all') q = q.eq('status', status);
    if (search) q = q.ilike('title', `%${search}%`);
    const { data } = await q;
    imported = (data || []).map((p) => ({ ...p, source: 'imported', date: p.wp_published_at }));
  }

  if (source === 'all' || source === 'native') {
    let q = supabase
      .from('native_articles')
      .select('id, title, author_name, category, featured_image, featured_image_alt, published_at, created_at, status, slug, scheduled_at, submitted_for_review_at')
      .order('created_at', { ascending: false });
    if (status !== 'all') q = q.eq('status', status);
    if (search) q = q.ilike('title', `%${search}%`);
    const { data } = await q;
    native = (data || []).map((p) => ({ ...p, source: 'native', date: p.published_at || p.created_at }));
  }

  return NextResponse.json({ imported, native });
}

// POST: create a new native article
export async function POST(req: NextRequest) {
  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 { title, excerpt, content, author_name, category, featured_image, featured_image_alt, status, slug } = body;

  if (!title || !slug) {
    return NextResponse.json({ error: 'Title and slug are required' }, { status: 400 });
  }

  const payload: Record<string, any> = {
    title,
    slug,
    excerpt: excerpt || null,
    content: content || null,
    author_name: author_name || null,
    category: category || null,
    featured_image: featured_image || null,
    featured_image_alt: featured_image_alt || null,
    status: status || 'draft',
  };

  if (status === 'published') {
    payload.published_at = new Date().toISOString();
  }
  if (status === 'pending') {
    payload.submitted_for_review_at = new Date().toISOString();
  }

  const { data, error } = await supabase.from('native_articles').insert(payload).select('id, title, excerpt, author_name, category, featured_image, featured_image_alt, slug').single();
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  // Trigger article publish notification if published immediately
  if (status === 'published' && data) {
    try {
      const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://avbeat.com';
      fetch(`${siteUrl}/api/newsletter/notify-article`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Cookie': req.headers.get('cookie') || '',
        },
        body: JSON.stringify({ article: data }),
      }).catch((err) => console.error('Article notification error:', err));
    } catch (notifyErr) {
      console.error('Failed to trigger article notification:', notifyErr);
    }
  }

  return NextResponse.json({ success: true, id: data?.id });
}

// PATCH: update article status or fields
export async function PATCH(req: NextRequest) {
  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 { id, source, updates } = body;

  if (!id || !source || !updates) {
    return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
  }

  const table = source === 'imported' ? 'wp_imported_posts' : 'native_articles';
  const payload: Record<string, any> = { ...updates };

  // If submitting for review (pending), record the timestamp
  if (updates.status === 'pending' && !payload.submitted_for_review_at) {
    payload.submitted_for_review_at = new Date().toISOString();
  }

  // If publishing, set published_at for native articles and clear scheduled_at
  if (updates.status === 'published') {
    if (source === 'native' && !updates.published_at) {
      payload.published_at = new Date().toISOString();
    }
    payload.scheduled_at = null;
  }

  // If scheduling: keep status as draft, set scheduled_at
  if (updates.scheduled_at && !updates.status) {
    payload.status = 'draft';
  }

  // If clearing schedule
  if (updates.scheduled_at === null) {
    payload.scheduled_at = null;
  }

  const { error } = await supabase.from(table).update(payload).eq('id', id);
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  // Trigger article publish notification when status changes to published
  if (updates.status === 'published') {
    try {
      const selectFields = source === 'imported' ?'id, title, excerpt, author_name, category, featured_image, featured_image_alt, wp_slug' :'id, title, excerpt, author_name, category, featured_image, featured_image_alt, slug';

      const { data: articleData } = await supabase
        .from(table)
        .select(selectFields)
        .eq('id', id)
        .single();

      if (articleData) {
        const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://avbeat.com';
        // Fire-and-forget: call notify-article route internally
        fetch(`${siteUrl}/api/newsletter/notify-article`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            // Pass auth cookie header for server-side auth
            'Cookie': req.headers.get('cookie') || '',
          },
          body: JSON.stringify({ article: articleData }),
        }).catch((err) => console.error('Article notification error:', err));
      }
    } catch (notifyErr) {
      // Non-fatal: log but don't fail the publish action
      console.error('Failed to trigger article notification:', notifyErr);
    }
  }

  return NextResponse.json({ success: true });
}

// DELETE: delete single or bulk articles
export async function DELETE(req: NextRequest) {
  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();
  // bulk: [{ id, source }] or single: { id, source }
  const items: { id: string; source: string }[] = body.items || [{ id: body.id, source: body.source }];

  const importedIds = items.filter((i) => i.source === 'imported').map((i) => i.id);
  const nativeIds = items.filter((i) => i.source === 'native').map((i) => i.id);

  if (importedIds.length > 0) {
    const { error } = await supabase.from('wp_imported_posts').delete().in('id', importedIds);
    if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  }

  if (nativeIds.length > 0) {
    const { error } = await supabase.from('native_articles').delete().in('id', nativeIds);
    if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  }

  return NextResponse.json({ success: true });
}
