"use server";

const API_KEY = process.env.BILLBEE_API_KEY as string;
const USERNAME = process.env.BILLBEE_USERNAME as string;
const API_PASSWORD = process.env.BILLBEE_PASSWORD as string;

const BASE_URL = "https://api.billbee.io/api/v1";

export interface OrderData {
  Bestellnummer: string | null;
  Sendungsnummer: string | null;
}

export interface RespError {
  orderId: string | null;
  error: string;
}

async function addShipment(orderId: string, shippingId: string) {
  const url = `${BASE_URL}/orders/${orderId}/shipment`;
  const headers: HeadersInit = {
    "X-Billbee-Api-Key": API_KEY,
    accept: "application/json",
    "Content-Type": "application/json",
    Authorization: "Basic " + btoa(`${USERNAME}:${API_PASSWORD}`),
  };

  const payload = {
    ShippingId: shippingId,
    ShippingProviderId: 6082,
    ShipmentType: 0,
  };

  const response = await fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload),
    credentials: "include", // Include credentials for basic auth
  });

  if (!response.ok) {
    throw new Error(`Error ${response.status}: ${await response.text()}`);
  }

  // Update order status
  const updateUrl = `${BASE_URL}/orders/${orderId}/orderstate`;
  const updatePayload = {
    NewStateId: 4,
  };

  const updateResponse = await fetch(updateUrl, {
    method: "PUT",
    headers: headers,
    body: JSON.stringify(updatePayload),
    credentials: "include",
  });

  if (!updateResponse.ok) {
    throw new Error(
      `Error updating order status ${
        updateResponse.status
      }: ${await updateResponse.text()}`
    );
  }
}

async function getByExternalId(externalId: string) {
  const url = `${BASE_URL}/orders/findbyextref/${externalId}`;
  const headers: HeadersInit = {
    "X-Billbee-Api-Key": API_KEY,
    accept: "application/json",
    Authorization: "Basic " + btoa(`${USERNAME}:${API_PASSWORD}`),
  };

  const response = await fetch(url, {
    method: "GET",
    headers: headers,
    credentials: "include",
  });

  if (!response.ok) {
    throw new Error(`Error ${response.status}: ${await response.text()}`);
  }

  return await response.json();
}

async function updateCompleteShipment(orderId: string, shippingId: string) {
  const res = await getByExternalId(orderId);
  const content = res.Data;
  const billbeeId = content.BillBeeOrderId;
  await addShipment(billbeeId, shippingId);
}

export async function main(data: OrderData[]) {
  const errors: RespError[] = [];

  for (const { Bestellnummer, Sendungsnummer } of data) {
    if (!Bestellnummer || !Sendungsnummer) {
      errors.push({
        orderId: Bestellnummer,
        error: "Order ID or Shipping ID is None",
      });
      continue;
    }

    try {
      await updateCompleteShipment(Bestellnummer, Sendungsnummer);
    } catch (e) {
      const errorMessage = e instanceof Error ? e.message : "Unknown error";
      console.error(`Error processing order ${Bestellnummer}: ${errorMessage}`);
      errors.push({ orderId: Bestellnummer, error: errorMessage });
    }
  }
  const result = {
    successful: data.length - errors.length,
    errors: errors,
  };
  return result;
}
