import { DrizzleService } from '@lib/drizzle/src';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { eq } from 'drizzle-orm';
import { tnMember } from 'drizzle/schema';
import * as admin from 'firebase-admin';
import { SendPushInput } from './fcm.type';

let app: admin.app.App;

const FCM_UNREGISTERED_TOKEN_ERROR_CODE =
  'messaging/registration-token-not-registered';

@Injectable()
export class FcmService {
  private logger = new Logger(FcmService.name);

  constructor(
    private configService: ConfigService,
    private drizzle: DrizzleService,
  ) {
    const privateKey = this.configService
      .get('fcm.privateKey')
      .replace(/\\n/g, '\n');
    const clientEmail = this.configService.get('fcm.clientEmail');
    const projectId = this.configService.get('fcm.projectId');

    app ??= admin.initializeApp({
      credential: admin.credential.cert({
        projectId,
        privateKey,
        clientEmail,
      }),
    });
  }

  async sendPush({
    title,
    body,
    token,
    redirectUri,
    almId,
    actionType,
    deepLink,
  }: SendPushInput) {
    const message: admin.messaging.Message = {
      notification: { title, body },
      token,
      data: {
        // 기존 필드 (하위 호환성 유지)
        redirectUri: redirectUri ?? '',
        alm_id: almId,
        // 새 딥링크 필드
        action_type: actionType || 'detail',
        deep_link: deepLink,
      },
    };

    //* 해당 에러 전파로 인해 이후 프로세스에 영향가지 않도록 토큰만 삭제 조치
    await app
      .messaging()
      .send(message)
      .catch(async (e) => {
        this.logger.error(e);

        if (e.code === 'messaging/registration-token-not-registered') {
          //* 유효하지 않은 토큰 삭제 조치
          await this.drizzle
            .update(tnMember)
            .set({
              memFcmToken: null,
            })
            .where(eq(tnMember.memFcmToken, token));
        }
      });
  }
}
