import AmbientConfig  from "../config/AmbientConfig";
import { Guard } from "../utils/Guard";

export class AmbientRestAPI{
    private _baseUrl: string;    
    constructor(private _config:AmbientConfig) {
        this._baseUrl = `https://${_config.server}/ambient`;
    }

    private getURL(path: string): string {
        return `${this._baseUrl}${path}`;
    }

    private async makePostRequest(url:string, requestData:object):Promise<any>{
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            throw error;
        }
    }    

    async GetNoteParams(): Promise<any> {
        const url = this.getURL('/note-params');
        const requestData = {
            SubscriptionCode: this._config.subscriptionCode,
            AccessKey: this._config.accessKey,
            UserTag: this._config.userTag
        };    
        return await this.makePostRequest(url, requestData);
    }

    async FetchJob(_jobId:string): Promise<any> {
        Guard.Against.NullOrEmpty(_jobId, 'Job Id');
        const url = this.getURL('/fetch-job');
        const requestData = {
            SubscriptionCode: this._config.subscriptionCode,
            AccessKey: this._config.accessKey,
            UserTag: this._config.userTag,
            JobID:_jobId
        };    
        return await this.makePostRequest(url, requestData);
    }

    async SendFinalNote(_jobId:string, _noteDate:string): Promise<any> {
        Guard.Against.NullOrEmpty(_jobId, 'Job Id');
        Guard.Against.NullOrEmpty(_noteDate, 'Note Data');
        const url = this.getURL('/send-final-note');
        const requestData = {
            SubscriptionCode: this._config.subscriptionCode,
            AccessKey: this._config.accessKey,
            UserTag: this._config.userTag,
            JobID:_jobId,
            SoapData: _noteDate
        };    
        return await this.makePostRequest(url, requestData);
    }
}