import { Injectable } from "@nestjs/common";
import type { NotificationPreference } from "../notifications/notifications.schema.js";
import * as repo from "./preferences.repository.js";
import type { UpdatePreferencesDto } from "./preferences.dto.js";

/**
 * PreferenceService —— 用户通知偏好管理。
 *
 * 职责：
 * - 查询用户偏好列表
 * - 批量 upsert 用户偏好（按 type 隔离）
 *
 * 仲裁依据 02-architecture-design.md §2.3：偏好按 (userId, type) 隔离。
 */
@Injectable()
export class PreferencesService {
  async getByUserId(userId: string): Promise<NotificationPreference[]> {
    return repo.findByUserId(userId);
  }

  async update(dto: UpdatePreferencesDto): Promise<void> {
    for (const pref of dto.preferences) {
      await repo.upsert(dto.userId, {
        type: pref.type,
        channels: pref.channels,
        frequencyLimit: pref.frequencyLimit ?? null,
        quietHoursStart: pref.quietHoursStart ?? null,
        quietHoursEnd: pref.quietHoursEnd ?? null,
        quietHoursTimezone: pref.quietHoursTimezone ?? "Asia/Shanghai",
        enabled: pref.enabled,
      });
    }
  }
}
