/home/bdqbpbxa/dev-subdomains/admin.pixory.goodface.com.ua/src/editor/editor.service.ts
import axios from 'axios';
import { env } from '../config/env';
import { errors } from '@strapi/utils';
import { ApplicationError } from '@strapi/utils/dist/errors';
import { Project } from '../api/order/project/common/types/project';
import { HttpStatus } from 'src/api/common/http-status';

const { NotFoundError, UnauthorizedError } = errors;

export class EditorService {
  public async getProject(projectId: string, userId: string): Promise<Project>{
    try {
      const url = `${this.getHost()}/project-cms/${projectId}`;
      
      const headers = {
        'X-User-Id': userId,
        'Authorization': `Bearer ${await this.generateEditorJwt()}`
      };
      
      const response = await axios.get(url, { headers });

      return response.data as Project;
    } catch (error) {
      const msg = error.response?.data?.message || error.message || 'Failed to fetch project from editor service';
      let responseError: ApplicationError<any>
      
      if (error.response?.status === HttpStatus.NotFound) {
        responseError = new NotFoundError(msg, { status: HttpStatus.NotFound });

      } else if (error.response?.status === HttpStatus.Unauthorized) {
        responseError = new UnauthorizedError(msg, { status: HttpStatus.Unauthorized });

      } else {
        responseError = new ApplicationError(msg, {
          status: error.response?.status || HttpStatus.InternalServerError,
          cause: error,
        });
      }

      throw responseError;
    }
  }

  public getHost(): string {
    return env.editor.host;
  }

  public async generateEditorJwt(): Promise<string> {
    try{
     const response = await axios.post(`${env.auth0.issuerBaseUrl}oauth/token`, {
        "client_id": env.auth0.clientId,
        "client_secret": env.auth0.clientSecret,
        "audience": env.editor.audience,
        "grant_type":"client_credentials"
      },
      {
        headers: { 'content-type': 'application/json' }
      });

      return response.data.access_token;
    } catch (error) {
      strapi.log.error('Error fetching token:', error);
    }
  }
}