import { Injectable } from '@nestjs/common';
import {
  Notification as PrismaNotification,
  NotificationType as PrismaNotificationType,
  NotificationPriority as PrismaPriority,
  TargetType as PrismaTargetType,
} from '@prisma/client';
import {
  NotificationEntity,
  NotificationType,
  NotificationPriority,
  TargetType,
  NotificationTarget,
} from '../../../domain/entities/notification.entity';

/**
 * 带关联数据的通知
 */
export interface NotificationWithTargets extends PrismaNotification {
  targetTags?: { tagId: string }[];
  targetUsers?: { accountSequence: string }[];
}

@Injectable()
export class NotificationMapper {
  toDomain(prisma: NotificationWithTargets): NotificationEntity {
    // 构建目标配置
    let targetConfig: NotificationTarget | null = null;
    const targetType = prisma.targetType as TargetType;

    if (targetType === TargetType.BY_TAG && prisma.targetTags?.length) {
      targetConfig = {
        type: targetType,
        tagIds: prisma.targetTags.map((t) => t.tagId),
      };
    } else if (
      targetType === TargetType.SPECIFIC &&
      prisma.targetUsers?.length
    ) {
      targetConfig = {
        type: targetType,
        accountSequences: prisma.targetUsers.map((u) => u.accountSequence),
      };
    } else if (targetType !== TargetType.ALL) {
      targetConfig = { type: targetType };
    }

    return new NotificationEntity(
      prisma.id,
      prisma.title,
      prisma.content,
      prisma.type as NotificationType,
      prisma.priority as NotificationPriority,
      targetType,
      targetConfig,
      prisma.imageUrl,
      prisma.linkUrl,
      prisma.isEnabled,
      prisma.requiresForceRead,
      prisma.publishedAt,
      prisma.expiresAt,
      prisma.createdAt,
      prisma.updatedAt,
      prisma.createdBy,
    );
  }

  toPersistence(
    entity: NotificationEntity,
  ): Omit<PrismaNotification, 'id'> & { id: string } {
    return {
      id: entity.id,
      title: entity.title,
      content: entity.content,
      type: entity.type as PrismaNotificationType,
      priority: entity.priority as PrismaPriority,
      targetType: entity.targetType as PrismaTargetType,
      targetLogic: 'ANY', // 默认 ANY，后续可扩展
      imageUrl: entity.imageUrl,
      linkUrl: entity.linkUrl,
      isEnabled: entity.isEnabled,
      requiresForceRead: entity.requiresForceRead,
      publishedAt: entity.publishedAt,
      expiresAt: entity.expiresAt,
      createdAt: entity.createdAt,
      updatedAt: entity.updatedAt,
      createdBy: entity.createdBy,
    };
  }
}
