import "server-only";

type MercadoPreferenceItem = {
  id: string;
  title: string;
  quantity: number;
  unit_price: number;
  currency_id: string;
};

type CreatePreferenceInput = {
  externalReference: string;
  payerEmail: string;
  items: MercadoPreferenceItem[];
  successUrl: string;
  failureUrl: string;
  pendingUrl: string;
  notificationUrl: string;
};

type MercadoPayment = {
  id: number;
  status: string;
  external_reference?: string;
  order?: {
    id?: string;
  };
};

const DEFAULT_MERCADO_API_BASE_URL = "https://api.mercadopago.com";

function getMercadoApiBaseUrl() {
  return (process.env.MP_API_BASE_URL?.trim() || process.env.MERCADO_PAGO_API_BASE_URL?.trim() || DEFAULT_MERCADO_API_BASE_URL).replace(/\/+$/, "");
}

export function getMercadoPagoAccessToken() {
  return process.env.MP_ACCESS_TOKEN?.trim() || process.env.MERCADO_PAGO_ACCESS_TOKEN?.trim() || "";
}

export function hasMercadoPagoConfig() {
  return Boolean(getMercadoPagoAccessToken());
}

function getHeaders(idempotencyKey?: string) {
  const accessToken = getMercadoPagoAccessToken();

  if (!accessToken) {
    throw new Error("Mercado Pago access token is not configured.");
  }

  const headers: Record<string, string> = {
    Authorization: `Bearer ${accessToken}`,
    "Content-Type": "application/json",
  };

  if (idempotencyKey) {
    headers["X-Idempotency-Key"] = idempotencyKey;
  }

  return headers;
}

export async function createMercadoPreference(input: CreatePreferenceInput) {
  const response = await fetch(`${getMercadoApiBaseUrl()}/checkout/preferences`, {
    method: "POST",
    headers: getHeaders(input.externalReference),
    body: JSON.stringify({
      items: input.items,
      payer: {
        email: input.payerEmail,
      },
      external_reference: input.externalReference,
      back_urls: {
        success: input.successUrl,
        failure: input.failureUrl,
        pending: input.pendingUrl,
      },
      auto_return: "approved",
      notification_url: input.notificationUrl,
    }),
    cache: "no-store",
  });

  const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;

  if (!response.ok || !payload) {
    throw new Error("No fue posible crear la preferencia en Mercado Pago.");
  }

  return {
    id: typeof payload.id === "string" ? payload.id : "",
    initPoint: typeof payload.init_point === "string" ? payload.init_point : "",
    sandboxInitPoint: typeof payload.sandbox_init_point === "string" ? payload.sandbox_init_point : "",
    rawPayload: payload,
  };
}

export async function fetchMercadoPaymentById(paymentId: string) {
  const response = await fetch(`${getMercadoApiBaseUrl()}/v1/payments/${encodeURIComponent(paymentId)}`, {
    method: "GET",
    headers: getHeaders(),
    cache: "no-store",
  });

  const payload = (await response.json().catch(() => null)) as MercadoPayment | null;

  if (!response.ok || !payload) {
    throw new Error("No fue posible consultar el pago en Mercado Pago.");
  }

  return payload;
}
