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

export async function GET(request: NextRequest) {
  // Get API key from authorization header
  const apiKey = request.headers.get("authorization");

  // Validate API key
  if (apiKey !== process.env.APP_API_KEY) {
    return NextResponse.json(
      { success: false, message: 'Unauthorized Access' },
      { status: 401 }
    );
  }

  const connection = await pool.getConnection();

  try {
    // Get query parameters for filtering
    const { searchParams } = new URL(request.url);
    const year = searchParams.get('year');
    const month = searchParams.get('month');
    const limit = parseInt(searchParams.get('limit') || '100');
    
    let query = 'SELECT id, title, description, image, created_at FROM tbl_announcements WHERE 1=1';
    const params: any[] = [];

    // Apply filters
    if (year) {
      query += ' AND YEAR(created_at) = ?';
      params.push(parseInt(year));
    }
    
    if (month) {
      query += ' AND MONTH(created_at) = ?';
      params.push(parseInt(month));
    }
    
    query += ' ORDER BY created_at DESC LIMIT ?';
    params.push(limit);

    const [announcements] = await connection.query<RowDataPacket[]>(query, params);

    // Get unique years for filter options (for frontend)
    const [yearsResult] = await connection.query<RowDataPacket[]>(
      'SELECT DISTINCT YEAR(created_at) as year FROM tbl_announcements ORDER BY year DESC'
    );

    return NextResponse.json({
      success: true,
      data: announcements,
      filters: {
        availableYears: yearsResult.map(row => row.year)
      }
    }, { status: 200 });

  } catch (err: any) {
    console.error("❌ GET API Error:", err);
    return NextResponse.json({ 
      success: false, 
      message: "Failed to fetch announcements", 
      error: err.message 
    }, { status: 500 });
  } finally {
    connection.release();
  }
}