import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { NotificationType } from '@prisma/client';

interface CreateNotificationOptions {
  type: NotificationType;
  title: string;
  body: string;
  payload?: Record<string, any>;
  fcmToken?: string | null;
}

@Injectable()
export class NotificationsService {
  constructor(private prisma: PrismaService) {}

  async create(userId: string, opts: CreateNotificationOptions) {
    const notification = await this.prisma.notification.create({
      data: {
        userId,
        type: opts.type,
        title: opts.title,
        body: opts.body,
        payload: opts.payload,
      },
    });

    if (opts.fcmToken) {
      await this.sendPush(opts.fcmToken, opts.title, opts.body, opts.payload);
    }

    return notification;
  }

  async findAll(userId: string) {
    return this.prisma.notification.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });
  }

  async markRead(id: string, userId: string) {
    return this.prisma.notification.update({
      where: { id },
      data: { read: true },
    });
  }

  async markAllRead(userId: string) {
    return this.prisma.notification.updateMany({
      where: { userId, read: false },
      data: { read: true },
    });
  }

  private async sendPush(token: string, title: string, body: string, data?: Record<string, any>) {
    // Firebase Admin SDK push notification — initialized separately via firebase-admin
    try {
      const admin = await import('firebase-admin');
      if (!admin.apps.length) return;
      await admin.messaging().send({ token, notification: { title, body }, data: data as any });
    } catch (err) {
      console.error('FCM error:', err);
    }
  }
}
