import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
import { inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { catchError, throwError } from 'rxjs';
import { SessionNoticeService } from '../services/session-notice.service';
import { AuthService } from '../services/auth.service';

export const sessionInterceptor: HttpInterceptorFn = (req, next) => {
  const platformId = inject(PLATFORM_ID);
  if (!isPlatformBrowser(platformId)) {
    return next(req);
  }

  const sessionNotice = inject(SessionNoticeService);
  const authService = inject(AuthService);

  const url = (req.url || '').toLowerCase();
  const isAuthRequest = url.includes('/auth/login') || url.includes('/auth/register');

  return next(req).pipe(
    catchError((err: HttpErrorResponse) => {
      if (err?.status === 401) {
        // 401 durante /auth/login = credenciais inválidas, não "sessão expirada".
        if (!isAuthRequest && !!authService.token) {
          sessionNotice.handleUnauthorized();
        }
      } else if (err?.status === 403) {
        sessionNotice.handleForbidden();
      }
      return throwError(() => err);
    })
  );
};
