import { Injectable } from '@nestjs/common';
import { UserPreferencesRepository } from './user-preferences.repository';
import { DEFAULT_USER_PREFERENCE } from './user.types';
import type { UpdateUserPreferenceDto, UserPreference } from './user.types';

@Injectable()
export class UserPreferencesService {
  constructor(private readonly repository: UserPreferencesRepository) {}

  async getOrDefault(userId: string): Promise<UserPreference> {
    const stored = await this.repository.findByUserId(userId);
    return stored ?? { userId, ...DEFAULT_USER_PREFERENCE };
  }

  async upsert(
    userId: string,
    dto: UpdateUserPreferenceDto,
  ): Promise<UserPreference> {
    const current = await this.getOrDefault(userId);
    return this.repository.upsert(userId, {
      preferredPace:
        dto.preferredPace !== undefined
          ? dto.preferredPace
          : current.preferredPace,
      preferredBudgetLevel:
        dto.preferredBudgetLevel !== undefined
          ? dto.preferredBudgetLevel
          : current.preferredBudgetLevel,
      maxWalkingDistanceKm:
        dto.maxWalkingDistanceKm !== undefined
          ? dto.maxWalkingDistanceKm
          : current.maxWalkingDistanceKm,
      preferredStartTime:
        dto.preferredStartTime !== undefined
          ? dto.preferredStartTime
          : current.preferredStartTime,
      childFriendlyPreferred:
        dto.childFriendlyPreferred !== undefined
          ? dto.childFriendlyPreferred
          : current.childFriendlyPreferred,
      interests:
        dto.interests !== undefined ? dto.interests : current.interests,
      notes: dto.notes !== undefined ? dto.notes : current.notes,
    });
  }
}
