import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject, of, throwError } from 'rxjs';
import { tap, delay } from 'rxjs/operators';

interface LoginCredentials {
  username?: string;
  password?: string;
  email?: string;
}

interface AuthResponse {
  token: string;
  user: {
    id: number;
    username: string;
    name: string;
    role: string;
    email?: string;
  };
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private apiUrl = 'api/auth';
  private userSubject = new BehaviorSubject<any>(null);
  public user$ = this.userSubject.asObservable();
  
  // Usuarios de prueba para simular login
  private mockUsers = [
    {
      email: 'admin@example.com',
      password: 'admin123',
      user: {
        id: 1,
        username: 'admin',
        name: 'Administrador',
        role: 'admin',
        email: 'admin@example.com'
      }
    },
    {
      email: 'user@example.com',
      password: 'user123',
      user: {
        id: 2,
        username: 'user',
        name: 'Usuario',
        role: 'user',
        email: 'user@example.com'
      }
    }
  ];
  
  constructor(private http: HttpClient) {
    // Check if user is already logged in on service initialization
    const user = localStorage.getItem('user');
    if (user) {
      this.userSubject.next(JSON.parse(user));
    }
  }

  login(credentials: LoginCredentials): Observable<AuthResponse> {
    // Simular login con usuarios de prueba
    const user = this.mockUsers.find(u => 
      u.email === credentials.email && u.password === credentials.password);
    
    if (user) {
      // Generar token falso
      const mockResponse: AuthResponse = {
        token: 'mock-jwt-token-' + Math.random().toString(36).substring(2, 15),
        user: user.user
      };
      
      return of(mockResponse).pipe(
        // Simular retraso de red
        delay(800),
        tap(response => {
          // Store token and user info
          localStorage.setItem('token', response.token);
          localStorage.setItem('user', JSON.stringify(response.user));
          this.userSubject.next(response.user);
        })
      );
    } else {
      // Simular error de credenciales inválidas
      return throwError(() => new Error('Credenciales incorrectas'));
    }
  }

  logout(): void {
    // Clear storage and update subject
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    this.userSubject.next(null);
  }

  isLoggedIn(): boolean {
    return !!localStorage.getItem('token');
  }

  getToken(): string | null {
    return localStorage.getItem('token');
  }

  getCurrentUser(): any {
    return this.userSubject.value;
  }
}