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

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const topic = searchParams.get('topic') || '';
    const year = searchParams.get('year') || '';
    const month = searchParams.get('month') || '';

    // Use service role or anon — templates are public read via this route
    const supabase = await createClient();

    let query = supabase
      .from('newsletter_templates')
      .select('id, name, description, layout, subject_prefix, header_text, accent_color, article_blocks, created_at, updated_at')
      .order('created_at', { ascending: false });

    // Filter by year
    if (year) {
      const start = `${year}-01-01T00:00:00.000Z`;
      const end = `${parseInt(year) + 1}-01-01T00:00:00.000Z`;
      query = query.gte('created_at', start).lt('created_at', end);
    }

    // Filter by month (requires year too)
    if (year && month) {
      const paddedMonth = month.padStart(2, '0');
      const nextMonth = parseInt(month) === 12 ? '01' : String(parseInt(month) + 1).padStart(2, '0');
      const nextYear = parseInt(month) === 12 ? String(parseInt(year) + 1) : year;
      const start = `${year}-${paddedMonth}-01T00:00:00.000Z`;
      const end = `${nextYear}-${nextMonth}-01T00:00:00.000Z`;
      query = query.gte('created_at', start).lt('created_at', end);
    }

    const { data, error } = await query;

    if (error) {
      console.error('Archive fetch error:', error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    let newsletters = data || [];

    // Filter by topic (article_blocks contain category fields)
    if (topic) {
      const topicLower = topic.toLowerCase();
      newsletters = newsletters.filter((n) => {
        const blocks = Array.isArray(n.article_blocks) ? n.article_blocks : [];
        const nameMatch = n.name?.toLowerCase().includes(topicLower);
        const descMatch = n.description?.toLowerCase().includes(topicLower);
        const blockMatch = blocks.some(
          (b: { category?: string; title?: string }) =>
            b.category?.toLowerCase().includes(topicLower) ||
            b.title?.toLowerCase().includes(topicLower)
        );
        return nameMatch || descMatch || blockMatch;
      });
    }

    // Derive available years from all records for filter UI
    const { data: allDates } = await supabase
      .from('newsletter_templates')
      .select('created_at')
      .order('created_at', { ascending: false });

    const years = Array.from(
      new Set((allDates || []).map((r) => new Date(r.created_at).getFullYear()))
    ).sort((a, b) => b - a);

    return NextResponse.json({ newsletters, years, total: newsletters.length });
  } catch (err) {
    console.error('Archive error:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
