import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { environment } from '../environments/environment';

export interface CfConfig {
  apiEndpoint: string;
  username: string;
  password: string;
  organization: string;
  space: string;
  appName: string;
  skipSslValidation: boolean;
}

export interface InitUploadResponse {
  success: boolean;
  uploadSessionId: string;
  message: string;
}

export interface ChunkUploadResponse {
  success: boolean;
  uploadSessionId: string;
  message: string;
}

export interface FinalizeResponse {
  uploadSessionId: string;
  status: string;
  message: string;
  progress: number;
}

export interface DeploymentStatus {
  uploadSessionId: string;
  status: string;
  message: string;
  progress: number;
  output?: string;
  error?: string;
}

@Injectable({
  providedIn: 'root'
})
export class DeployService {
  private apiBase = environment.apiBase;

  constructor(private http: HttpClient) {}

  async initUpload(config: CfConfig): Promise<InitUploadResponse> {
    const url = `${this.apiBase}/upload/init`;
    return firstValueFrom(
      this.http.post<InitUploadResponse>(url, config)
    );
  }

  async uploadChunk(
    sessionId: string,
    fileType: string,
    fileName: string,
    chunkIndex: number,
    totalChunks: number,
    base64Data: string
  ): Promise<ChunkUploadResponse> {
    const url = `${this.apiBase}/upload/chunk?uploadSessionId=${sessionId}&fileType=${fileType}&chunkIndex=${chunkIndex}&totalChunks=${totalChunks}&fileName=${encodeURIComponent(fileName)}`;

    const headers = new HttpHeaders({
      'Content-Type': 'text/plain',
      'X-Chunk-Encoding': 'base64'
    });

    return firstValueFrom(
      this.http.post<ChunkUploadResponse>(url, base64Data, { headers })
    );
  }

  async finalizeUpload(sessionId: string): Promise<FinalizeResponse> {
    const url = `${this.apiBase}/upload/finalize?uploadSessionId=${sessionId}&async=true`;

    const headers = new HttpHeaders({
      'Content-Length': '0'
    });

    return firstValueFrom(
      this.http.post<FinalizeResponse>(url, null, { headers })
    );
  }

  async getDeploymentStatus(sessionId: string): Promise<DeploymentStatus> {
    const url = `${this.apiBase}/deployment/status/${sessionId}`;
    return firstValueFrom(
      this.http.get<DeploymentStatus>(url)
    );
  }
}
