// app/api/push-tokens/cleanup/route.ts
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { ResultSetHeader } from 'mysql2';

export async function POST(request: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    // ============ ADMIN ONLY - CHECK API_KEY ============
    const authHeader = request.headers.get('authorization');
    
    if (authHeader !== process.env.APP_API_KEY) {
      return NextResponse.json({
        success: false,
        message: "Unauthorized Access"
      }, { status: 401 });
    }

    // Delete tokens older than 90 days that are inactive
    const [result] = await connection.query<ResultSetHeader>(
      `DELETE FROM push_tokens 
       WHERE is_active = FALSE 
       AND last_used_at < DATE_SUB(NOW(), INTERVAL 90 DAY)
       OR (last_used_at IS NULL AND created_at < DATE_SUB(NOW(), INTERVAL 30 DAY))`
    );

    return NextResponse.json({
      success: true,
      message: `Cleaned up ${result.affectedRows} old tokens`,
      data: { deletedCount: result.affectedRows }
    }, { status: 200 });

  } catch (err: any) {
    console.error("Cleanup error:", err);
    return NextResponse.json({
      success: false,
      message: "Internal server error",
      error: err.message
    }, { status: 500 });
  } finally {
    connection.release();
  }
}