import { Injectable, OnDestroy, inject } from '@angular/core';
import { interval, Subscription } from 'rxjs';
import { DietService } from './diet.service';
import { AuthService } from './auth.service';
import { DueReminder } from '../models/diet.models';
import { todayIso } from '../models/diet.models';

@Injectable({ providedIn: 'root' })
export class ReminderNotificationService implements OnDestroy {
  private readonly diet = inject(DietService);
  private readonly auth = inject(AuthService);
  private sub: Subscription | null = null;
  private readonly notifiedIds = new Set<number>();

  start(): void {
    if (this.sub || !this.auth.isAuthenticated()) return;
    this.requestPermission();
    this.poll();
    this.sub = interval(60_000).subscribe(() => this.poll());
  }

  stop(): void {
    this.sub?.unsubscribe();
    this.sub = null;
    this.notifiedIds.clear();
  }

  ngOnDestroy(): void {
    this.stop();
  }

  private requestPermission(): void {
    if (typeof Notification === 'undefined') return;
    if (Notification.permission === 'default') {
      void Notification.requestPermission();
    }
  }

  private poll(): void {
    if (!this.auth.isAuthenticated()) return;
    const now = new Date();
    const time = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    this.diet.getDueReminders(todayIso(), time).subscribe({
      next: (due) => this.showNotifications(due),
      error: () => {},
    });
  }

  private showNotifications(due: DueReminder[]): void {
    if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return;
    for (const r of due) {
      if (this.notifiedIds.has(r.id)) continue;
      this.notifiedIds.add(r.id);
      const body = r.message ?? undefined;
      new Notification(r.title, { body, tag: `reminder-${r.id}` });
    }
    if (this.notifiedIds.size > 100) {
      this.notifiedIds.clear();
    }
  }
}
