import { AuthConfig } from 'angular-oauth2-oidc';
import { OAuthModuleConfig } from 'angular-oauth2-oidc';

import { environment } from '../environments/environment';

/** Public origin for same-origin deploys when environment URLs are left empty. */
function publicOrigin(): string {
	return window.location.origin;
}

function resolveIdentityServer(): string {
	const configured = (environment.identityServer ?? '').trim();
	if (configured) {
		return configured.endsWith('/') ? configured : `${configured}/`;
	}
	return `${publicOrigin()}/`;
}

function resolveAllowedUrls(): string[] {
	const configured = environment.allowedUrls ?? [];
	if (configured.length > 0) {
		return configured;
	}
	const origin = publicOrigin();
	const api = (environment.apiUrl ?? '').trim().replace(/\/$/, '');
	return api ? [origin, api] : [origin];
}

export const AuthCodeFlowConfig: AuthConfig = {
	// Url of the Identity Provider
	issuer: resolveIdentityServer(),
	// Local/Docker HTTP demos can set environment.requireHttps = false.
	requireHttps: (environment as { requireHttps?: boolean }).requireHttps ?? environment.production,
	strictDiscoveryDocumentValidation:
		(environment as { requireHttps?: boolean }).requireHttps ?? environment.production,

	// URL of the SPA to redirect the user to after login
	redirectUri: window.location.origin + '/',
	// Password/external grants issue refresh tokens; no cookie session for iframe silent refresh.
	useSilentRefresh: false,
	sessionChecksEnabled: false,
	timeoutFactor: 0.75,

	clientId: 'angulartemplate_spa',

	// Authorization Code + PKCE for interactive OIDC; email/password still uses ROPC (see docs/AUTH.md).
	responseType: 'code',
	disablePKCE: false,

	// offline_access → refresh_token (used by setupAutomaticSilentRefresh)
	scope: 'openid profile email api offline_access',

	showDebugInformation: !environment.production,
};

export const AuthModuleConfig: OAuthModuleConfig = {
	resourceServer: {
		allowedUrls: resolveAllowedUrls(),
		sendAccessToken: true,
	}
};
