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

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

export async function OPTIONS() {
  return NextResponse.json({}, { status: 200 });
}

export async function DELETE(request: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    // ============ VALIDATION FOR UNAUTHENTICATED ACCESS ============
    const authHeader = request.headers.get('authorization');
    let isAuthenticated = false;
    let authenticatedUserId: number | null = null;
    
    if (authHeader && authHeader.startsWith('Bearer ')) {
      const token = authHeader.substring(7);
      const authResult = await verifyAuthentication(token);
      
      if (!(authResult instanceof NextResponse)) {
        const decoded = authResult as TokenInterface;
        if (decoded && decoded.id) {
          authenticatedUserId = decoded.id;
          isAuthenticated = true;
        }
      }
    } else if (authHeader !== process.env.APP_API_KEY) {
      return NextResponse.json({
        success: false,
        message: "Unauthorized Access"
      }, { status: 401 });
    }

    const body = await request.json();
    const { token, tokenType } = body;

    if (!token) {
      return NextResponse.json({
        success: false,
        message: "Token is required"
      }, { status: 400 });
    }

    await connection.beginTransaction();

    let deleteResult: ResultSetHeader;
    
    if (isAuthenticated && authenticatedUserId) {
      // Delete by user ID and token
      if (tokenType === 'expo') {
        [deleteResult] = await connection.query<ResultSetHeader>(
          `DELETE FROM push_tokens 
           WHERE user_id = ? AND expo_push_token = ?`,
          [authenticatedUserId, token]
        );
      } else {
        [deleteResult] = await connection.query<ResultSetHeader>(
          `DELETE FROM push_tokens 
           WHERE user_id = ? AND firebase_token = ?`,
          [authenticatedUserId, token]
        );
      }
    } else {
      // Delete by token only (for guest users)
      if (tokenType === 'expo') {
        [deleteResult] = await connection.query<ResultSetHeader>(
          `DELETE FROM push_tokens WHERE expo_push_token = ? AND user_id IS NULL`,
          [token]
        );
      } else {
        [deleteResult] = await connection.query<ResultSetHeader>(
          `DELETE FROM push_tokens WHERE firebase_token = ? AND user_id IS NULL`,
          [token]
        );
      }
    }

    await connection.commit();

    return NextResponse.json({
      success: true,
      message: "Push token deleted successfully",
      data: {
        affectedRows: deleteResult.affectedRows
      }
    }, { status: 200 });

  } catch (err: any) {
    try {
      await connection.rollback();
    } catch (rollbackErr) {
      console.error("Rollback failed:", rollbackErr);
    }

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