import { forbidden, unauthorized } from "@/modules/auth/errors";
import {
  isKnownCustomer,
  listEnvCustomerIds,
  resetServiceTokenEnvCache,
  resolveEnvServiceToken,
  type VerifiedServiceToken,
} from "@/modules/auth/service-token-env";

export type { VerifiedServiceToken } from "@/modules/auth/service-token-env";
export {
  isKnownCustomer,
  listEnvCustomerIds,
  listRegisteredCustomerIds,
  parseServiceToken,
  parseServiceTokenFromEnv,
  verifyServiceToken,
  verifyServiceTokenFromEnv,
} from "@/modules/auth/service-token-env";

/** 测试专用：重置 env 缓存 */
export function resetServiceTokenCache(): void {
  resetServiceTokenEnvCache();
}

/** 异步：env + 数据库活跃客户 */
export async function listAllCustomerIds(): Promise<string[]> {
  const { listActiveDbCustomerIds } = await import(
    "@/modules/customer/customer-service"
  );
  const dbIds = await listActiveDbCustomerIds();
  return [...new Set([...listEnvCustomerIds(), ...dbIds])].sort();
}

export async function isKnownCustomerAsync(
  customerId: string,
): Promise<boolean> {
  if (isKnownCustomer(customerId)) {
    return true;
  }
  const { isDbCustomerActive } = await import(
    "@/modules/customer/customer-service"
  );
  return isDbCustomerActive(customerId);
}

/** env + DB 完整校验（API 路由用，勿在 middleware 引用本文件） */
export async function verifyServiceTokenAsync(
  token: string,
  customerId?: string,
): Promise<VerifiedServiceToken> {
  const fromEnv = resolveEnvServiceToken(token, customerId);
  if (fromEnv) {
    return fromEnv;
  }

  const { resolveDbServiceToken } = await import(
    "@/modules/customer/customer-service"
  );
  const fromDb = await resolveDbServiceToken(token);
  if (!fromDb) {
    throw unauthorized("Service Token 无效");
  }
  if (customerId && fromDb.customerId !== customerId) {
    throw forbidden("customer_id 与令牌租户不匹配");
  }
  return fromDb;
}
