import { Injectable, inject } from '@angular/core';
import { Router } from '@angular/router';
import { finalize } from 'rxjs';
import { AuthService } from './auth.service';
import { PermissionService } from './permission.service';
import { SessionService } from './session.service';
import { Permission } from '../models/permission.model';

/**
 * Public surface for components/pages. Components should depend on this,
 * not on AuthService/SessionService/PermissionService directly, so the
 * orchestration details (which service owns what) can change without
 * touching UI code.
 */
@Injectable({ providedIn: 'root' })
export class AuthFacade {
  private readonly auth = inject(AuthService);
  private readonly session = inject(SessionService);
  private readonly permissions = inject(PermissionService);
  private readonly router = inject(Router);

  readonly isAuthenticated = this.session.isAuthenticated;
  readonly status = this.session.status;
  readonly role = this.session.role;
  readonly loginPhase = this.auth.loginPhase;
  readonly lastError = this.auth.lastError;

  restoreSession(): void {
    this.auth.restoreSession();
  }

  login(onSuccessRedirectTo?: string): void {
    this.auth.login().subscribe({
      next: () => {
        if (onSuccessRedirectTo) {
          this.router.navigateByUrl(onSuccessRedirectTo);
        }
      },
      error: () => {
        const code = this.auth.lastError()?.code ?? 'unauthorized';
        this.router.navigate(['/admin-login/error', code]);
      }
    });
  }

  logout(redirectTo = '/admin-login'): void {
    this.auth
      .logout()
      .pipe(finalize(() => this.router.navigateByUrl(redirectTo)))
      .subscribe({ error: () => undefined });
  }

  can(permission: Permission): boolean {
    return this.permissions.has(permission);
  }
}
