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

const DEFAULT_CATEGORIES = [
  { name: "Tech", slug: "tech", is_active: 1, sort_order: 1 },
  { name: "News", slug: "news", is_active: 1, sort_order: 2 },
  { name: "Lifestyle", slug: "lifestyle", is_active: 1, sort_order: 3 },
];

export async function GET(request: NextRequest) {
  const comingHeaders = request.headers.get("authorization");

  if (comingHeaders !== process.env.APP_API_KEY) {
    return NextResponse.json(
      { success: false, message: "Unauthorized Access" },
      { status: 401 }
    );
  }

  try {
    // Check if categories exist
    const [rows] = await pool.query<RowDataPacket[]>(
      "SELECT COUNT(*) AS count FROM blog_category"
    );

    const count = rows[0].count as number;

    // Insert default categories if empty
    if (count === 0) {
      const insertQuery = `
        INSERT INTO blog_category (name, slug, is_active, sort_order)
        VALUES ?
      `;

      const defaultCategoryValues = DEFAULT_CATEGORIES.map((category) => [
        category.name,
        category.slug,
        category.is_active,
        category.sort_order,
      ]);

      await pool.query(insertQuery, [defaultCategoryValues]);
      console.log("✅ Default categories inserted");
    }

    // Fetch categories
    const [categories] = await pool.query<RowDataPacket[]>(
      "SELECT * FROM blog_category ORDER BY sort_order ASC"
    );

    return NextResponse.json({ success: true, data: categories });
  } catch (error) {
    console.error("Error fetching categories:", error);
    return NextResponse.json(
      { success: false, message: "Server error" },
      { status: 500 }
    );
  }
}