import { Injectable } from '@nestjs/common';
import { PrismaService } from '@modules/shared';
import { type NotificationPreferenceEntity } from '../../domain/entities/notification-preference.entity';
import { type INotificationPreferenceRepository } from '../../domain/repositories/notification-preference.repository';
import { type NotificationChannel } from '../../domain/value-objects/notification-channel.vo';

@Injectable()
export class PrismaNotificationPreferenceRepository implements INotificationPreferenceRepository {
  constructor(private readonly prisma: PrismaService) {}

  async findByUserId(userId: string): Promise<NotificationPreferenceEntity[]> {
    const records = await this.prisma.notificationPreference.findMany({
      where: { userId },
    });
    return records as NotificationPreferenceEntity[];
  }

  async isEnabled(userId: string, channel: NotificationChannel, eventType: string): Promise<boolean> {
    const pref = await this.prisma.notificationPreference.findUnique({
      where: { userId_channel_eventType: { userId, channel, eventType } },
    });
    // Default to enabled if no preference record exists
    return pref?.enabled ?? true;
  }

  async upsert(
    userId: string,
    channel: NotificationChannel,
    eventType: string,
    enabled: boolean,
  ): Promise<NotificationPreferenceEntity> {
    const record = await this.prisma.notificationPreference.upsert({
      where: { userId_channel_eventType: { userId, channel, eventType } },
      create: { userId, channel, eventType, enabled },
      update: { enabled },
    });
    return record as NotificationPreferenceEntity;
  }
}
