import { json, type RequestHandler } from '@sveltejs/kit';
import { BackendAuth, AuthConfigManager } 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 GET: RequestHandler = async () => {
  try {
    const { token, expiresOnISO } = await backendAuth.graphTokenManager.getTokenWithExpiry();
    
    if (!token) {
      return json({ success: false, error: 'Failed to acquire Graph token' }, { status: 500 });
    }
    
    // Decode JWT to show token details (for verification)
    const parts = token.split('.');
    let payload: any = {};
    if (parts.length === 3) {
      try {
        const decoded = JSON.parse(Buffer.from(parts[1], 'base64').toString());
        payload = {
          aud: decoded.aud,
          iss: decoded.iss,
          scp: decoded.scp,
          app_displayname: decoded.app_displayname,
          iat: new Date(decoded.iat * 1000).toISOString(),
          exp: new Date(decoded.exp * 1000).toISOString(),
        };
      } catch (e) {
        // Silent fail - just show truncated token
      }
    }
    
    return json({
      success: true,
      token: token.substring(0, 50) + '...',
      fullToken: token, // Include full token for testing
      expiresOn: expiresOnISO,
      isValid: backendAuth.graphTokenManager.isTokenValid(),
      tokenDetails: Object.keys(payload).length > 0 ? payload : 'Could not decode',
    });
  } catch (error) {
    return json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to acquire token' },
      { status: 500 }
    );
  }
};
