import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' })
export class SessionService {
  private inactivityTimeout = 30 * 60 * 1000; // 30 minutes

  constructor(private router: Router, private authService: AuthService) {
    this.setupActivityListeners();
    this.checkInactivity();
  }

  private setupActivityListeners() {
    window.addEventListener('mousemove', this.resetTimer.bind(this));
    window.addEventListener('keypress', this.resetTimer.bind(this));
    window.addEventListener('scroll', this.resetTimer.bind(this));
    window.addEventListener('click', this.resetTimer.bind(this));
  }

  private resetTimer() {
    localStorage.setItem('lastActivity', Date.now().toString());
  }

  private checkInactivity() {
    setInterval(() => {
      const lastActivity = localStorage.getItem('lastActivity');
      if (lastActivity) {
        const currentTime = Date.now();
        const elapsedTime = currentTime - parseInt(lastActivity, 10);
        
        if (elapsedTime > this.inactivityTimeout) {
          this.authService.logout().subscribe(() => {
            sessionStorage.clear();
            localStorage.clear();
            this.router.navigate(['/login']);
          });
        }
      }
    }, 60000); // Check every minute
  }
}