// app/api/appapis/logout/route.ts
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-api-key',
  'Access-Control-Allow-Credentials': 'true',
};

export async function OPTIONS() {
  return new NextResponse(null, {
    status: 204,
    headers: corsHeaders,
  });
}

export async function POST(req: NextRequest) {
  const incomingHeaders = req.headers.get("authorization");

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

  try {
    const body = await req.json();
    const { refreshToken } = body;
    
    // Clear refresh token from database if provided
    if (refreshToken) {
      try {
        await pool.query(
          "UPDATE users SET refresh_token = NULL WHERE refresh_token = ?",
          [refreshToken]
        );
      } catch (error) {
        console.error('Error clearing refresh token:', error);
      }
    }
    
    const response = NextResponse.json({
      success: true,
      message: "Logout Successful"
    }, { headers: corsHeaders });

    // Clear cookies
    response.cookies.set('app-token', "", { 
      httpOnly: true, 
      expires: new Date(0),
      path: '/'
    });
    
    response.cookies.set('app-refresh-token', "", { 
      httpOnly: true, 
      expires: new Date(0),
      path: '/'
    });

    return response;
  } catch (error: unknown) {
    const errorMessage = (error as Error).message || "Something went wrong. Please try again!";
  
    return NextResponse.json(
      {
        success: false,
        message: errorMessage,
      },
      {
        status: 500,
        headers: corsHeaders
      }
    );
  }
}