import { Injectable, computed, signal } from '@angular/core';
import { User } from '../../models/user.model';

@Injectable({ providedIn: 'root' })
export class AuthStore {
  private static readonly TOKEN_KEY = 'tw_token';
  private static readonly USER_KEY = 'tw_user';

  private readonly tokenSignal = signal<string | null>(AuthStore.readToken());
  private readonly userSignal = signal<User | null>(AuthStore.readStoredUser());

  readonly token = this.tokenSignal.asReadonly();
  readonly currentUser = this.userSignal.asReadonly();
  readonly isLoggedIn = computed(() => this.tokenSignal() !== null);

  setSession(token: string, user: User): void {
    localStorage.setItem(AuthStore.TOKEN_KEY, token);
    localStorage.setItem(AuthStore.USER_KEY, JSON.stringify(user));
    this.tokenSignal.set(token);
    this.userSignal.set(user);
  }

  clearSession(): void {
    localStorage.removeItem(AuthStore.TOKEN_KEY);
    localStorage.removeItem(AuthStore.USER_KEY);
    this.tokenSignal.set(null);
    this.userSignal.set(null);
  }

  updateUser(user: User): void {
    localStorage.setItem(AuthStore.USER_KEY, JSON.stringify(user));
    this.userSignal.set(user);
  }

  private static readToken(): string | null {
    try {
      return localStorage.getItem(AuthStore.TOKEN_KEY);
    } catch {
      return null;
    }
  }

  private static readStoredUser(): User | null {
    try {
      const raw = localStorage.getItem(AuthStore.USER_KEY);
      return raw ? (JSON.parse(raw) as User) : null;
    } catch {
      return null;
    }
  }
}
