import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AppConfigService } from './config.service';

@Injectable({ providedIn: 'root' })
export class ApiEndpointInterceptor implements HttpInterceptor {
    constructor(private readonly configService: AppConfigService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return this.prependUrl(req, next);
    }

    prependUrl(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const apiEndpoint = this.configService.setting.apiEndpoint;
        if (apiEndpoint === undefined || !this.configService.loaded)
            throw new Error('API endpoint is not defined or config not loaded');
        
        const isRelative = !/^https?:\/\//i.test(req.url);
        const url = isRelative ? `${apiEndpoint.replace(/\/$/, '')}/${req.url.replace(/^\//, '')}` : req.url;
        const cloned = req.clone({ url });
        console.trace('ApiEndpointInterceptor hit:', url);
        return next.handle(cloned);
    }
}
