import pool from "../../../../lib/db/db";
import { NextResponse, NextRequest } from "next/server";

export async function GET(request: NextRequest) {
    // Check authorization header
    const incomingHeaders = request.headers.get("authorization");

    if (incomingHeaders !== process.env.APP_API_KEY) {
        return NextResponse.json(
            { success: false, message: 'Unauthorized Access' },
            { status: 401 }
        );
    }
    
  try {
    const { searchParams } = new URL(request.url);

    const page = parseInt(searchParams.get("page") || "1", 10);
    const limit = parseInt(searchParams.get("limit") || "10", 10);
    const search = searchParams.get("search") || "";
    const startDate = searchParams.get("start_date") || "";
    const endDate = searchParams.get("end_date") || "";
    const popular = searchParams.get("popular") || "";
    const active = searchParams.get("active") || "";
    const country = searchParams.get("country") || "";
    const type = searchParams.get("type") || "";

    const skip = (page - 1) * limit;

    // Build WHERE conditions - ALWAYS include is_active = 1
    let where = "WHERE b.is_active = 1";
    let params: any[] = [];

    if (search) {
      where += " AND (b.title LIKE ? OR b.short_description LIKE ? OR b.description LIKE ?)";
      params.push(`%${search}%`, `%${search}%`, `%${search}%`);
    }

    if (startDate) {
      where += " AND b.created_at >= ?";
      params.push(`${startDate} 00:00:00`);
    }

    if (endDate) {
      where += " AND b.created_at <= ?";
      params.push(`${endDate} 23:59:59`);
    }

    if (popular !== "") {
      where += " AND b.is_featured = ?";
      params.push(popular === "true" ? 1 : 0);
    }

    // Debug final query
    console.log("📋 WHERE:", where, params);

    const conn = await pool.getConnection();

    try {
      // Count total with filters
      const [countRows] = await conn.query(
        `SELECT COUNT(*) as count FROM blogs b ${where}`,
        params
      );
      const totalCount = (countRows as any)[0].count;

      // Fetch paginated blogs with author information
      const [rows] = await conn.query(
        `
        SELECT 
          b.id, b.title, b.short_description, b.description, b.image, b.category_id, b.author_id,
          b.is_active, b.is_featured, b.enable_meta_tags, b.created_at, b.updated_at,
          b.custom_post_type, b.seo, b.post_attributes, b.views, b.likes, b.rating_count,
          b.review_count, b.avg_review_value, b.slug,
          a.full_name as author_name,
          a.slug as author_slug,
          a.profile_image as author_image
        FROM blogs b
        LEFT JOIN authors a ON b.author_id = a.id
        ${where}
        ORDER BY b.created_at DESC
        LIMIT ? OFFSET ?
      `,
        [...params, limit, skip]
      );

      const formattedPosts = (rows as any[]).map((post) => ({
        id: post.id,
        title: post.title,
        short_description: post.short_description,
        description: post.description,
        image: post.image,
        category_id: post.category_id,
        user_id: post.user_id,
        is_active: !!post.is_active,
        is_featured: !!post.is_featured,
        enable_meta_tags: !!post.enable_meta_tags,
        created_at: post.created_at,
        updated_at: post.updated_at,
        custom_post_type: post.custom_post_type,
        seo: post.seo,
        post_attributes: post.post_attributes,
        views: post.views,
        likes: post.likes,
        rating_count: post.rating_count,
        review_count: post.review_count,
        avg_review_value: post.avg_review_value,
        slug: post.slug,
        // Author information
        author: post.author_id ? {
          name: post.author_name,
          slug: post.author_slug,
          image: post.author_image
        } : null
      }));

      const totalPages = Math.ceil(totalCount / limit);

      return NextResponse.json({
        success: true,
        data: formattedPosts,
        pagination: {
          currentPage: page,
          totalPages,
          totalItems: totalCount,
          itemsPerPage: limit,
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1,
          startItem: skip + 1,
          endItem: Math.min(skip + formattedPosts.length, totalCount),
          actualItemsOnPage: formattedPosts.length,
        },
        filters: {
          country,
          search,
          startDate,
          endDate,
          popular,
          active: "1", // Since we're always filtering by active blogs
        },
      });
    } finally {
      conn.release();
    }
  } catch (err: any) {
    console.error("❌ GET API Error:", err);
    return NextResponse.json(
      {
        success: false,
        error: "Failed to fetch blogs",
        details: err.message,
      },
      { status: 500 }
    );
  }
}