import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { newsletterSubscribers } from '@/shared/schema';
import { eq, desc, sql, and } from 'drizzle-orm';

const SITE_ID = 'ten-sura-game.com';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const offset = (page - 1) * limit;

    // Fetch subscribers for the site
    const subscribers = await db
      .select()
      .from(newsletterSubscribers)
      .where(eq(newsletterSubscribers.siteId, SITE_ID))
      .limit(limit)
      .offset(offset)
      .orderBy(desc(newsletterSubscribers.subscribedAt));

    // Get total count
    const countResult = await db
      .select({ count: sql<number>`count(*)` })
      .from(newsletterSubscribers)
      .where(eq(newsletterSubscribers.siteId, SITE_ID));
    
    const totalCount = countResult[0].count;
    const totalPages = Math.ceil(totalCount / limit);

    return NextResponse.json({
      subscribers,
      totalCount,
      totalPages,
      currentPage: page,
    });
  } catch (error: any) {
    console.error('Error fetching subscribers:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
