import { Injectable } from '@angular/core';
import { JwtClaims } from '../models/auth-api.model';

/**
 * Client-side JWT *decoding* only - never verification. The signature is
 * meaningless to check here because the frontend has no trusted key to check
 * it against; verifying a JWT's signature is the backend's job on every
 * request. This service exists purely so the UI can read `role`/`exp` for
 * display and route-gating UX (e.g. "session expires in 4m").
 */
@Injectable({ providedIn: 'root' })
export class JwtService {
  decode(token: string): JwtClaims | null {
    const parts = token.split('.');
    if (parts.length !== 3) {
      return null;
    }

    try {
      const payload = this.base64UrlDecode(parts[1]);
      const claims = JSON.parse(payload) as JwtClaims;
      return this.isJwtClaims(claims) ? claims : null;
    } catch {
      return null;
    }
  }

  isExpired(claims: JwtClaims, skewSeconds = 0): boolean {
    return claims.exp * 1000 <= Date.now() + skewSeconds * 1000;
  }

  private isJwtClaims(value: unknown): value is JwtClaims {
    if (!value || typeof value !== 'object') {
      return false;
    }
    const claims = value as Partial<JwtClaims>;
    return typeof claims.sub === 'string' && typeof claims.role === 'string' && typeof claims.exp === 'number';
  }

  private base64UrlDecode(input: string): string {
    const base64 = input.replace(/-/g, '+').replace(/_/g, '/').padEnd(input.length + ((4 - (input.length % 4)) % 4), '=');
    return decodeURIComponent(escape(atob(base64)));
  }
}
