import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as webpush from 'web-push';
import type { Env } from '../config/env.schema';

export interface PushPayload {
  title: string;
  body: string;
  url?: string;
}

interface PushTarget {
  endpoint: string;
  p256dh: string;
  auth: string;
}

@Injectable()
export class PushService {
  private readonly logger = new Logger(PushService.name);
  private readonly enabled: boolean;

  constructor(config: ConfigService<Env, true>) {
    const publicKey = config.get('VAPID_PUBLIC_KEY', { infer: true });
    const privateKey = config.get('VAPID_PRIVATE_KEY', { infer: true });
    const contact = config.get('VAPID_CONTACT', { infer: true });

    if (publicKey && privateKey) {
      webpush.setVapidDetails(contact, publicKey, privateKey);
      this.enabled = true;
    } else {
      this.enabled = false;
      this.logger.warn(
        'VAPID não configurado — push desativado (defina VAPID_PUBLIC_KEY e VAPID_PRIVATE_KEY)',
      );
    }
  }

  async send(target: PushTarget, payload: PushPayload): Promise<void> {
    if (!this.enabled) return;
    try {
      await webpush.sendNotification(
        { endpoint: target.endpoint, keys: { p256dh: target.p256dh, auth: target.auth } },
        JSON.stringify(payload),
      );
    } catch (err: unknown) {
      // 410 Gone = subscription expirada; logar sem throw para não quebrar o fluxo principal
      this.logger.warn({ err }, `Push falhou para ${target.endpoint.slice(0, 60)}`);
    }
  }
}
