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

import {
  SESSION_COOKIE_NAME,
  expiredSessionCookies,
  getRequestHost,
  getSessionCookieHeader,
} from '@/services/auth';

import { reportApiError } from '@/utils/apiError';

import { authLogout } from '@/generated/azopus-api';

export async function POST(request: NextRequest) {
  const cookie = getSessionCookieHeader(request.cookies.get(SESSION_COOKIE_NAME)?.value);

  if (cookie) {
    try {
      // Revokes the session on the backend; the local cookie is removed either way.
      await authLogout({ headers: { Cookie: cookie }, cache: 'no-store' });
    } catch (error) {
      reportApiError(error, 'Logout request failed:');
    }
  }

  const response = NextResponse.json({ ok: true }, { headers: { 'Cache-Control': 'no-store' } });
  // The shared session cookie is only removed by a cookie with the same Domain and Path, which is
  // why every place it may be stored is expired (this also signs out of the admin app).
  for (const expired of expiredSessionCookies(getRequestHost(request.headers))) {
    response.headers.append('Set-Cookie', expired);
  }
  return response;
}
