import axios from "axios";

import { buildCommanderHeaders, resolveCommanderBaseUrl } from "./commanderHttp";

type ApiErrorShape = {
  error?: {
    message?: string;
  };
};

type PresignParceiroLogoResponse = {
  data: {
    uploadUrl: string;
    publicUrl: string;
    objectKey: string;
    expiresIn: number;
  };
};

export type PresignParceiroLogoPayload = {
  fileName: string;
  contentType: "image/jpeg" | "image/png" | "image/webp";
};

class FechamentoUploadsService {
  private handleAxiosError(error: unknown, fallback: string): never {
    if (axios.isAxiosError(error)) {
      if (!error.response) {
        throw new Error(
          "Não foi possível conectar na API do Commander. Verifique VITE_API_BASE_URL_COMMANDER e se o backend está acessível.",
        );
      }
      const message = ((error.response.data as ApiErrorShape | undefined)?.error?.message ??
        error.message ??
        fallback) as string;
      throw new Error(message);
    }
    throw new Error(fallback);
  }

  async presignUploadParceiroLogo(payload: PresignParceiroLogoPayload) {
    try {
      const headers = await buildCommanderHeaders();
      const baseUrl = resolveCommanderBaseUrl();
      const response = await axios.post<PresignParceiroLogoResponse>(
        `${baseUrl}/uploads/parceiros/logo/presign`,
        payload,
        { headers },
      );
      return response.data.data;
    } catch (error) {
      this.handleAxiosError(error, "Erro ao preparar upload da logo.");
    }
  }

  async uploadFileToSignedUrl(uploadUrl: string, file: File): Promise<void> {
    try {
      await axios.put(uploadUrl, file, {
        headers: {
          "Content-Type": file.type,
        },
      });
    } catch (error) {
      if (axios.isAxiosError(error)) {
        throw new Error(error.message || "Falha ao enviar arquivo para armazenamento.");
      }
      throw new Error("Falha ao enviar arquivo para armazenamento.");
    }
  }
}

export const fechamentoUploadsService = new FechamentoUploadsService();
