import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';

// ---------------------------------------------------------------------------
// POST /api/auth/logout
// ---------------------------------------------------------------------------
// Clears the httpOnly auth cookie and optionally invalidates the token on
// the Go API side.
// ---------------------------------------------------------------------------

const API_BASE_URL =
  process.env.API_URL ||
  process.env.NEXT_PUBLIC_API_URL ||
  'https://honeyDue.treytartt.com/api';

const COOKIE_NAME = 'honeydue-token';

export async function POST(request: NextRequest) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get(COOKIE_NAME)?.value;

    // Best-effort: tell the Go API to invalidate the token
    if (token) {
      try {
        await fetch(`${API_BASE_URL}/auth/logout/`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Token ${token}`,
          },
          cache: 'no-store',
        });
      } catch {
        // Don't block logout if the upstream call fails
      }
    }

    // Delete the cookie
    cookieStore.delete(COOKIE_NAME);

    return NextResponse.json({ message: 'Logged out successfully' });
  } catch (error) {
    console.error('[auth/logout] Error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 },
    );
  }
}
