import { json, type RequestHandler } from '@sveltejs/kit';
import { BackendAuth } from '$lib/auth/backend';

const backendAuth = new BackendAuth(
  {
    clientId: process.env.CLIENT_ID,
    tenantId: process.env.TENANT_ID,
    clientSecret: process.env.CLIENT_SECRET,
  },
  process.env.PB_DB
);

export const POST: RequestHandler = async () => {
  try {
    backendAuth.graphTokenManager.clearCache();
    const { token, expiresOnISO } = await backendAuth.graphTokenManager.getTokenWithExpiry();
    return json({
      success: true,
      refreshed: true,
      expiresOn: expiresOnISO,
    });
  } catch (error) {
    return json(
      { success: false, error: error instanceof Error ? error.message : 'Refresh failed' },
      { status: 500 }
    );
  }
};
