import { RowDataPacket } from "mysql2";
import pool from "../../../../../lib/db/db";
import { NextRequest } from "next/server";

interface PageProps {
    params: Promise<{ slug: string }>
}

export async function GET(
  request: NextRequest,
  { params }: PageProps
) {
  try {
    const { slug } = await params;
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page')) || 1;
    const limit = parseInt(searchParams.get('limit')) || 6;
    const contentType = searchParams.get('contentType') || 'all'; // 'articles', 'guides', 'all'

    console.log('🔍 Author API called with params:', { slug, page, limit, contentType });

    // Fetch author details
    const authorQuery = `
      SELECT 
        id,
        full_name,
        slug,
        bio,
        profile_image,
        website,
        social_facebook,
        social_twitter,
        social_instagram,
        social_linkedin,
        status,
        created_at,
        updated_at
      FROM authors 
      WHERE slug = ? AND status = 'active'
    `;

    const [authorRows] = await pool.query<RowDataPacket[]>(authorQuery, [slug]);
    
    if (authorRows.length === 0) {
      return Response.json({
        success: false,
        error: 'Author not found'
      }, { status: 404 });
    }

    const author = authorRows[0];
    const authorId = author.id;

    // Initialize content arrays
    let articles = [];
    let guides = [];
    let totalArticles = 0;
    let totalGuides = 0;

    // Fetch articles if needed
    if (contentType === 'all' || contentType === 'articles') {
      // Count total articles
      const articlesCountQuery = `
        SELECT COUNT(*) as total
        FROM blogs
        WHERE author_id = ? AND is_active = TRUE
      `;
      const [articlesCountRows] = await pool.query<RowDataPacket[]>(articlesCountQuery, [authorId]);
      totalArticles = articlesCountRows[0].total;

      // Fetch articles with pagination
      const articlesOffset = (page - 1) * limit;
      const articlesQuery = `
        SELECT 
          id,
          title,
          short_description,
          description,
          image,
          category_id,
          is_featured,
          created_at,
          updated_at,
          views,
          likes,
          rating_count,
          review_count,
          avg_review_value,
          slug
        FROM blogs
        WHERE author_id = ? AND is_active = TRUE
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
      `;
      const [articlesRows] = await pool.query<RowDataPacket[]>(articlesQuery, [authorId, limit, articlesOffset]);
      articles = articlesRows;

      // Get category names for articles
      if (articles.length > 0) {
        const articleIds = articles.map(article => article.id);
        const categoriesQuery = `
          SELECT 
            b.id as blog_id,
            c.name as category_name
          FROM blogs b
          LEFT JOIN blog_category c ON b.category_id = c.id
          WHERE b.id IN (?)
        `;
        const [categoriesRows] = await pool.query<RowDataPacket[]>(categoriesQuery, [articleIds]);
        
        // Map category names to articles
        const categoryMap = new Map();
        categoriesRows.forEach(row => {
          categoryMap.set(row.blog_id, row.category_name);
        });
        
        articles = articles.map(article => ({
          ...article,
          category_name: categoryMap.get(article.id) || 'Uncategorized'
        }));
      }
    }

    // Fetch guides if needed
    if (contentType === 'all' || contentType === 'guides') {
      // Count total guides
      const guidesCountQuery = `
        SELECT COUNT(*) as total
        FROM guides
        WHERE author_id = ? AND is_active = TRUE
      `;
      const [guidesCountRows] = await pool.query<RowDataPacket[]>(guidesCountQuery, [authorId]);
      totalGuides = guidesCountRows[0].total;

      // Fetch guides with pagination
      const guidesOffset = (page - 1) * limit;
      const guidesQuery = `
        SELECT 
          id,
          title,
          sub_title,
          description,
          image,
          guide_type,
          slug,
          is_featured,
          created_at,
          updated_at
        FROM guides
        WHERE author_id = ? AND is_active = TRUE
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
      `;
      const [guidesRows] = await pool.query<RowDataPacket[]>(guidesQuery, [authorId, limit, guidesOffset]);
      guides = guidesRows;
    }

    // Calculate pagination based on content type
    let totalItems, totalPages;
    
    if (contentType === 'all') {
      totalItems = totalArticles + totalGuides;
      totalPages = Math.ceil(totalItems / limit);
    } else if (contentType === 'articles') {
      totalItems = totalArticles;
      totalPages = Math.ceil(totalItems / limit);
    } else {
      totalItems = totalGuides;
      totalPages = Math.ceil(totalItems / limit);
    }

    return Response.json({
      success: true,
      data: {
        author: {
          ...author,
          stats: {
            articles: totalArticles,
            guides: totalGuides,
            totalContent: totalArticles + totalGuides
          }
        },
        content: {
          articles,
          guides
        },
        meta: {
          totalItems,
          totalPages,
          currentPage: page,
          limit,
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1
        }
      }
    });

  } catch (error) {
    console.error('🔍 Error in author API:', error);
    return Response.json({
      success: false,
      error: 'Failed to fetch author data',
      details: error.message
    }, { status: 500 });
  }
}