import { HttpService } from "@nestjs/axios";
import { Injectable } from "@nestjs/common";
import { map, take } from "rxjs";
import { PaperDto } from "../../domain/dtos";

/**
 * Upload service provider
 */
@Injectable()
export class UploadService {
    /**
     * Constructs the service with injection of
     * HTTPService instance
     * @param httpService 
     */
    constructor(private readonly httpService: HttpService) {}

    /**
     * Elastichsearch server port-number
     */
    private readonly ES_PORT = process.env.ES_PORT;
    
    /**
     * Elasticsearch IP address
     */
    private readonly ES_IP = process.env.ES_CONTAINER_NAME;
    
    /**
     * Uploads a paper
     * @returns
     */
    async upload(paperData: PaperDto): Promise<Object | any> {
        return new Promise((resolve, reject) => {
            try {
                (this.httpService.post(`http://${this.ES_IP}:${this.ES_PORT}/papers/_doc/`, {
                    data: paperData,
                    headers: {'Content-Type': 'application/json'},
                }))
                ?.pipe(take(1), map(axiosRes => axiosRes.data))
                .subscribe((res: Object | any) => {
                    resolve(res);
                });
            } catch (error) {
                reject(error);
            }
        });
    }
}