// src/app/services/auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private apiUrl = environment.apiUrl;

  constructor(private http: HttpClient, private router: Router) {}

  login(machineId: string, password: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/login`, { machine_id: machineId, password });
  }

  setLoggedInMachine(machineId: string, machineIdNum: number) {
    localStorage.setItem('loggedInMachineId', machineId);
    localStorage.setItem('loggedInMachineIdNum', machineIdNum.toString());
  }

  logout() {
    localStorage.removeItem('loggedInMachineId');
    localStorage.removeItem('loggedInMachineIdNum');
    this.router.navigate(['/login']);
  }

  getLoggedInMachineId(): string | null {
    return localStorage.getItem('loggedInMachineId');
  }

  getLoggedInMachineIdNum(): number | null {
    const idNum = localStorage.getItem('loggedInMachineIdNum');
    return idNum ? +idNum : null;
  }
}