import type {
  ChannelSendContext,
  ChannelSendResult,
  NotificationChannelStrategy,
} from "./channel.types.js";

/**
 * InAppChannel —— 站内信渠道。
 *
 * 站内信数据已在 NotificationService 中写入 MySQL + ES，
 * 此渠道仅负责触发 push-gateway 实时推送给在线用户（软失败）。
 *
 * 仲裁依据 02-architecture-design.md §2.4：
 * - in_app 总是发送，保证站内信可见
 * - 实时推送通过 push-gateway，不在线时用户下次拉取即可见
 */
import { sendPush } from "../shared/push/push-gateway.client.js";
import { logger } from "../shared/observability/logger.js";

class InAppChannel implements NotificationChannelStrategy {
  readonly name = "in_app" as const;

  async send(ctx: ChannelSendContext): Promise<ChannelSendResult> {
    // 站内信数据已落库，仅触发实时推送
    const pushResult = await sendPush({
      userId: ctx.userId,
      event: "notification.new",
      data: {
        id: ctx.notificationId,
        type: ctx.type,
        title: ctx.title,
        content: ctx.content,
        metadata: ctx.metadata,
      },
    });

    if (!pushResult.sent) {
      logger.debug(
        { userId: ctx.userId, notificationId: ctx.notificationId },
        "In-app push not delivered (user offline or gateway unavailable)",
      );
    }

    return {
      channel: "in_app",
      sent: true, // 站内信本身已成功（数据已落库），push 是增强
      externalId: pushResult.sent ? ctx.notificationId : undefined,
    };
  }
}

export const inAppChannel = new InAppChannel();
