import { cookies } from "next/headers";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { verifyAudienceJwt } from "@open-mercato/shared/lib/auth/jwt";
import { CUSTOMER_JWT_AUDIENCE } from "@open-mercato/core/modules/customer_accounts/services/customerSessionService";
import { tryNormalizeHostname } from "@open-mercato/core/modules/customer_accounts/lib/hostname";
import { platformDomains } from "@open-mercato/core/modules/customer_accounts/lib/platformDomains";
import { validateUserState } from "./customerAuth.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customer_accounts").child({ component: "customer-auth-server" });
async function assertSessionStillActive(sessionId) {
  try {
    const container = await createRequestContainer();
    const service = container.resolve("customerSessionService");
    const session = await service.findActiveSessionById(sessionId);
    return session !== null;
  } catch {
    return false;
  }
}
async function getCustomerAuthFromCookies(options) {
  const cookieStore = await cookies();
  const token = cookieStore.get("customer_auth_token")?.value;
  if (!token) return null;
  try {
    const payload = verifyAudienceJwt(CUSTOMER_JWT_AUDIENCE, token);
    if (!payload) return null;
    if (payload.type !== "customer") return null;
    const sid = typeof payload.sid === "string" ? payload.sid : "";
    if (!sid) return null;
    const tenantId = String(payload.tenantId);
    if (options?.expectedTenantId && options.expectedTenantId !== tenantId) {
      return null;
    }
    const stillActive = await assertSessionStillActive(sid);
    if (!stillActive) return null;
    const userState = await validateUserState(
      String(payload.sub),
      tenantId,
      String(payload.orgId),
      payload.iat
    );
    if (!userState.valid) return null;
    return {
      sub: String(payload.sub),
      sid,
      type: "customer",
      tenantId,
      orgId: String(payload.orgId),
      email: String(payload.email || ""),
      displayName: String(payload.displayName || ""),
      customerEntityId: payload.customerEntityId ? String(payload.customerEntityId) : null,
      personEntityId: payload.personEntityId ? String(payload.personEntityId) : null,
      resolvedFeatures: userState.resolvedFeatures
    };
  } catch {
    return null;
  }
}
async function getCustomerAuthForHost(host) {
  if (!host) return getCustomerAuthFromCookies();
  try {
    const hostname = tryNormalizeHostname(host);
    if (!hostname) return getCustomerAuthFromCookies();
    if (platformDomains().includes(hostname)) return getCustomerAuthFromCookies();
    const container = await createRequestContainer();
    const service = container.resolve("domainMappingService");
    const resolved = await service.resolveByHostname(hostname);
    if (!resolved || resolved.status !== "active") return null;
    return getCustomerAuthFromCookies({ expectedTenantId: resolved.tenantId });
  } catch (err) {
    logger.warn("Domain resolve failed; falling back to platform cookie", { err });
    return getCustomerAuthFromCookies();
  }
}
export {
  getCustomerAuthForHost,
  getCustomerAuthFromCookies
};
//# sourceMappingURL=customerAuthServer.js.map
