import { Injectable } from '@nestjs/common';
import { FirebaseService } from './firebase-admin.service';
import { InjectRepository } from '@nestjs/typeorm';
import { DeviceToken } from '@/entities/device-token.entity';
import { Repository } from 'typeorm';
import { ANDROID, WEB } from '@/common/constant';

@Injectable()
export class PushService {
  constructor(
    private firebase: FirebaseService,
    @InjectRepository(DeviceToken)
    private deviceRepo: Repository<DeviceToken>,
  ) {}

  async sendToUser(userId: string, payload: any) {
    const devices = await this.deviceRepo.find({
      where: { user: { id: userId } },
    });

    const expoTokens = devices
      .filter((d) => d.platform === ANDROID)
      .map((d) => d.token);

    const fcmTokens = devices
      .filter((d) => d.platform === WEB)
      .map((d) => d.token);

    if (expoTokens.length) {
      await fetch('https://exp.host/--/api/v2/push/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(
          expoTokens.map((token) => ({
            to: token,
            title: payload.title,
            body: payload.body,
            data: {
              groupId: payload.groupId ?? "",
              tripId: payload.tripId ?? "",
              type: payload.type ?? ""
            },
          })),
        ),
      });
    }

    // 🔥 2. gửi Firebase (web)
    if (fcmTokens.length) {
      await this.firebase.sendAndCleanup(
        fcmTokens,
        payload,
        async (badToken) => {
          await this.deviceRepo.delete({ token: badToken });
        },
      );
    }
  }
}
