import { Injectable, inject, signal, computed } from '@angular/core';
import { Observable, tap } from 'rxjs';
import { ApiService } from './api.service';
import { LoginResponse, User } from '../models/types';

const STORAGE_KEY = 'metacourse_user';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private readonly api = inject(ApiService);

  currentUser = signal<LoginResponse | null>(null);
  isLoggedIn = computed(() => this.currentUser() !== null);

  constructor() {
    this.loadFromStorage();
  }

  login(email: string, password: string): Observable<LoginResponse> {
    return this.api.post<LoginResponse>('/api/users/login', { email, password }).pipe(
      tap(user => {
        this.currentUser.set(user);
        localStorage.setItem(STORAGE_KEY, JSON.stringify(user));
      })
    );
  }

  register(name: string, email: string, password: string): Observable<User> {
    return this.api.post<User>('/api/users/register', { name, email, password });
  }

  logout(): void {
    this.currentUser.set(null);
    localStorage.removeItem(STORAGE_KEY);
  }

  loadFromStorage(): void {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const user = JSON.parse(stored) as LoginResponse;
        this.currentUser.set(user);
      }
    } catch {
      localStorage.removeItem(STORAGE_KEY);
    }
  }
}
