import { NotificationPreference } from '@core/notifications/domain/entities/NotificationPreference';
import type { NotificationPreferenceRepository } from '@core/notifications/domain/repositories/NotificationPreferenceRepository';
import type { DataSource } from 'typeorm';
import { NotificationPreferenceOrmEntity } from '../entities/NotificationPreferenceOrmEntity';
import { NotificationPreferenceOrmMapper } from '../mappers/NotificationPreferenceOrmMapper';

export class TypeOrmNotificationPreferenceRepository implements NotificationPreferenceRepository {
  constructor(
    private readonly dataSource: DataSource,
    private readonly mapper: NotificationPreferenceOrmMapper,
  ) {}

  async findByDriverId(driverId: string): Promise<NotificationPreference | null> {
    const repo = this.dataSource.getRepository(NotificationPreferenceOrmEntity);
    const entity = await repo.findOne({ where: { driverId } });
    return entity ? this.mapper.toDomain(entity) : null;
  }

  async save(preference: NotificationPreference): Promise<void> {
    const repo = this.dataSource.getRepository(NotificationPreferenceOrmEntity);
    const entity = this.mapper.toOrmEntity(preference);
    await repo.save(entity);
  }

  async delete(driverId: string): Promise<void> {
    const repo = this.dataSource.getRepository(NotificationPreferenceOrmEntity);
    await repo.delete({ driverId });
  }

  async getOrCreateDefault(driverId: string): Promise<NotificationPreference> {
    const existing = await this.findByDriverId(driverId);
    if (existing) {
      return existing;
    }

    const defaultPrefs = NotificationPreference.createDefault(driverId);
    await this.save(defaultPrefs);
    return defaultPrefs;
  }
}