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

interface TokenInterface {
  id: number;
  userId?: number;
  email?: string;
  role?: string;
}

interface PushTokenRow extends RowDataPacket {
  id: number;
  expo_push_token: string | null;
  firebase_token: string | null;
  platform: string;
  device_brand: string;
  os_version: string;
  is_active: boolean;
  last_used_at: Date;
}

export async function GET(request: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    // Get auth token from header
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "Authentication required"
      }, { status: 401 });
    }

    const token = authHeader.substring(7);
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as TokenInterface;
    
    if (!decoded || !decoded.id) {
      return NextResponse.json({
        success: false,
        message: "Invalid token"
      }, { status: 401 });
    }

    // Get all active tokens for the user
    const [tokens] = await connection.query<PushTokenRow[]>(
      `SELECT id, expo_push_token, firebase_token, platform, 
              device_brand, os_version, is_active, last_used_at
       FROM push_tokens 
       WHERE user_id = ? AND is_active = TRUE
       ORDER BY last_used_at DESC`,
      [decoded.id]
    );

    return NextResponse.json({
      success: true,
      data: tokens,
      count: tokens.length
    }, { status: 200 });

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