"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientConfigService = void 0;
const common_1 = require("@nestjs/common");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const tenant_service_1 = require("../../tenant/services/tenant.service");
let ClientConfigService = class ClientConfigService {
    authConfig;
    tenantService;
    constructor(authConfig, tenantService) {
        this.authConfig = authConfig;
        this.tenantService = tenantService;
    }
    async getClientConfig() {
        const config = this.authConfig.getConfig();
        const tenants = await this.fetchTenants();
        const defaultTenantId = await this.resolveDefaultTenantId(config.defaultTenant);
        const ssoProviders = [];
        if (config.google) {
            const googleAuthUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
            googleAuthUrl.searchParams.set('client_id', config.google.clientId);
            googleAuthUrl.searchParams.set('redirect_uri', config.google.redirectUri);
            googleAuthUrl.searchParams.set('response_type', 'code');
            googleAuthUrl.searchParams.set('scope', 'openid email profile');
            googleAuthUrl.searchParams.set('access_type', 'offline');
            googleAuthUrl.searchParams.set('prompt', 'consent');
            ssoProviders.push({
                id: 'google',
                name: 'Google',
                logoUrl: 'https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg',
                hint: 'Sign in with Google',
                clientId: config.google.clientId,
                authorizationUrl: googleAuthUrl.toString(),
            });
        }
        if (config.facebook) {
            const facebookAuthUrl = new URL('https://www.facebook.com/v18.0/dialog/oauth');
            facebookAuthUrl.searchParams.set('client_id', config.facebook.appId);
            facebookAuthUrl.searchParams.set('redirect_uri', config.facebook.redirectUri);
            facebookAuthUrl.searchParams.set('scope', 'email');
            facebookAuthUrl.searchParams.set('response_type', 'code');
            ssoProviders.push({
                id: 'facebook',
                name: 'Facebook',
                logoUrl: 'https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/facebook.svg',
                hint: 'Sign in with Facebook',
                clientId: config.facebook.appId,
                authorizationUrl: facebookAuthUrl.toString(),
            });
        }
        if (config.apple) {
            ssoProviders.push({
                id: 'apple',
                name: 'Apple',
                logoUrl: undefined,
                hint: 'Sign in with Apple',
            });
        }
        if (config.github) {
            const githubAuthUrl = new URL('https://github.com/login/oauth/authorize');
            githubAuthUrl.searchParams.set('client_id', config.github.clientId);
            githubAuthUrl.searchParams.set('redirect_uri', config.github.redirectUri);
            githubAuthUrl.searchParams.set('scope', 'user:email');
            githubAuthUrl.searchParams.set('response_type', 'code');
            ssoProviders.push({
                id: 'github',
                name: 'GitHub',
                logoUrl: 'https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png',
                hint: 'Sign in with GitHub',
                clientId: config.github.clientId,
                authorizationUrl: githubAuthUrl.toString(),
            });
        }
        const defaultConfig = {
            emailAuth: {
                enabled: config.emailAuth?.enabled ?? false,
            },
            phoneAuth: {
                enabled: config.phoneAuth?.enabled ?? false,
            },
            registration: {
                enabled: config.registration?.enabled !== false,
                requireInvitation: config.registration?.requireInvitation ?? false,
                collectProfileFields: config.registration?.collectProfileFields,
            },
            mfa: {
                enabled: config.mfa?.enabled ?? false,
                methods: config.mfa?.methods?.map((m) => m.toString()) ?? [],
                allowUserToggle: config.mfa?.allowUserToggle ?? true,
                allowMethodSelection: config.mfa?.allowMethodSelection ?? true,
            },
            tenants: {
                mode: config.defaultTenant ? 'single' : 'multi',
                defaultTenantId,
                options: tenants,
            },
            sso: {
                enabled: Boolean(config.google || config.facebook || config.apple || config.github),
                providers: ssoProviders,
            },
        };
        if (config.clientConfig?.factory) {
            const customized = await config.clientConfig.factory(defaultConfig, {
                configService: this.authConfig,
                tenantService: this.tenantService,
            });
            return customized ?? defaultConfig;
        }
        return defaultConfig;
    }
    async fetchTenants() {
        try {
            const tenants = await this.tenantService.getTenants({
                select: ['id', 'name', 'slug', 'metadata', 'isActive'],
                order: { name: 'ASC' },
            });
            return tenants.map((tenant) => ({
                id: tenant.id,
                name: tenant.name,
                slug: tenant.slug,
                metadata: tenant.metadata ?? {},
                isActive: tenant.isActive,
            }));
        }
        catch (error) {
            return [];
        }
    }
    async resolveDefaultTenantId(options) {
        if (!options?.slug && !options?.domain) {
            return null;
        }
        try {
            const tenant = options.slug
                ? await this.tenantService.getTenantBySlug(options.slug)
                : await this.tenantService.getTenantByDomain(options.domain);
            return tenant?.id ?? null;
        }
        catch (error) {
            return null;
        }
    }
};
exports.ClientConfigService = ClientConfigService;
exports.ClientConfigService = ClientConfigService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [auth_config_service_1.AuthConfigService,
        tenant_service_1.TenantService])
], ClientConfigService);
//# sourceMappingURL=client-config.service.js.map