import { t as env } from "../env.js";
import { U as generateId } from "../utils.js";
import "../logger.js";
import "../schema-conversion.js";
import { f as ssoProvider } from "../auth-schema.js";
import "../auth-detection.js";
import { i as ownerRole, n as adminRole, r as memberRole, t as ac } from "../permissions.js";
import { eq } from "drizzle-orm";
import { sso } from "@better-auth/sso";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { bearer, deviceAuthorization, organization } from "better-auth/plugins";

//#region src/auth/auth.ts
/**
* Extracts the root domain from a URL for cross-subdomain cookie sharing.
* For example:
* - https://manage-api.pilot.inkeep.com -> .pilot.inkeep.com
* - https://pilot.inkeep.com -> .pilot.inkeep.com
* - http://localhost:3002 -> undefined (no domain for localhost)
*
* The logic extracts the parent domain that can be shared across subdomains.
* For domains with 3+ parts, it takes everything except the first part.
* For domains with exactly 2 parts, it takes both parts.
*/
function extractCookieDomain(baseURL) {
	try {
		const hostname = new URL(baseURL).hostname;
		if (hostname === "localhost" || hostname.match(/^\d+\.\d+\.\d+\.\d+$/)) return;
		const parts = hostname.split(".");
		if (parts.length < 2) return;
		let domainParts;
		if (parts.length === 3) domainParts = parts;
		else if (parts.length > 3) domainParts = parts.slice(1);
		else domainParts = parts;
		return `.${domainParts.join(".")}`;
	} catch {
		return;
	}
}
async function registerSSOProvider(dbClient, provider) {
	try {
		if ((await dbClient.select().from(ssoProvider).where(eq(ssoProvider.providerId, provider.providerId)).limit(1)).length > 0) return;
		if (!provider.domain) throw new Error(`SSO provider '${provider.providerId}' must have a domain`);
		await dbClient.insert(ssoProvider).values({
			id: generateId(),
			providerId: provider.providerId,
			issuer: provider.issuer,
			domain: provider.domain,
			oidcConfig: provider.oidcConfig ? JSON.stringify(provider.oidcConfig) : null,
			samlConfig: provider.samlConfig ? JSON.stringify(provider.samlConfig) : null,
			userId: null,
			organizationId: provider.organizationId || null
		});
	} catch (error) {
		console.error(`❌ Failed to register SSO provider '${provider.providerId}':`, error);
	}
}
function createAuth(config) {
	const cookieDomain = extractCookieDomain(config.baseURL);
	const auth$1 = betterAuth({
		baseURL: config.baseURL,
		secret: config.secret,
		database: drizzleAdapter(config.dbClient, { provider: "pg" }),
		emailAndPassword: {
			enabled: true,
			minPasswordLength: 8,
			maxPasswordLength: 128,
			requireEmailVerification: false,
			autoSignIn: true
		},
		socialProviders: config.socialProviders?.google && { google: config.socialProviders.google },
		session: {
			expiresIn: 3600 * 24 * 7,
			updateAge: 3600 * 24,
			cookieCache: {
				enabled: true,
				maxAge: 300,
				strategy: "compact"
			}
		},
		advanced: {
			crossSubDomainCookies: {
				enabled: true,
				...cookieDomain && { domain: cookieDomain }
			},
			defaultCookieAttributes: {
				sameSite: "none",
				secure: true,
				httpOnly: true,
				partitioned: true,
				...cookieDomain && { domain: cookieDomain }
			},
			...config.advanced
		},
		trustedOrigins: [
			"http://localhost:3000",
			"http://localhost:3002",
			env.INKEEP_AGENTS_MANAGE_UI_URL,
			env.INKEEP_AGENTS_MANAGE_API_URL
		].filter((origin) => typeof origin === "string" && origin.length > 0),
		plugins: [
			bearer(),
			sso(),
			organization({
				allowUserToCreateOrganization: true,
				ac,
				roles: {
					member: memberRole,
					admin: adminRole,
					owner: ownerRole
				},
				membershipLimit: 300,
				invitationLimit: 300,
				invitationExpiresIn: 10080 * 60,
				async sendInvitationEmail(data) {
					console.log("📧 Invitation created:", {
						email: data.email,
						invitedBy: data.inviter.user.name || data.inviter.user.email,
						organization: data.organization.name,
						invitationId: data.id
					});
				}
			}),
			deviceAuthorization({
				verificationUri: "/device",
				expiresIn: "60m",
				interval: "5s",
				userCodeLength: 8
			})
		]
	});
	if (config.ssoProviders?.length) {
		const providers = config.ssoProviders;
		setTimeout(async () => {
			for (const provider of providers) await registerSSOProvider(config.dbClient, provider);
		}, 1e3);
	}
	return auth$1;
}
const auth = null;

//#endregion
export { auth, createAuth };
//# sourceMappingURL=auth.js.map