"use server";

import { revalidatePath } from "next/cache";
import { getTranslations } from "@/i18n/server";
import { parseErrorMessage } from "@/lib/api-error";
import { sdpApiRequest } from "@/lib/sdp-api";
import type { CreateAssetDraftInput, CreateAssetDraftResult } from "./draft-mapping";

/**
 * Create an issued-token draft together with its Asset Profile in a single call.
 *
 * `POST /v1/issuance/asset-profiles` writes the token row and the profile row in
 * one DB transaction, so there is no orphan-token failure mode to recover from:
 * either both are created or neither is.
 */
export async function createAssetDraftAction(
  input: CreateAssetDraftInput
): Promise<CreateAssetDraftResult> {
  const t = await getTranslations();
  const { token } = input;

  const payload: Record<string, unknown> = {
    name: token.name,
    symbol: token.symbol,
    template: token.template,
    requiresAllowlist: token.requiresAllowlist,
    // Unconditional: `false` is meaningful here, and omitting it would let the
    // API default back to `true` and grant the mint a freeze authority the
    // issuer explicitly declined.
    isFreezable: token.isFreezable,
    assetCategory: input.assetCategory,
    assetType: input.assetType,
    issuanceMetadata: input.issuanceMetadata,
  };

  const decimals = Number.parseInt(token.decimals, 10);
  if (Number.isInteger(decimals)) {
    payload.decimals = decimals;
  }
  if (token.description) {
    payload.description = token.description;
  }
  if (token.uri) {
    payload.uri = token.uri;
  }
  if (token.imageUrl) {
    payload.imageUrl = token.imageUrl;
  }
  if (token.signingWalletId) {
    payload.signingWalletId = token.signingWalletId;
  }
  // Absent = uncapped. buildTokenInput already drops a blank cap, and the API's
  // decimal-string refinement would reject "".
  if (token.maxSupply) {
    payload.maxSupply = token.maxSupply;
  }

  try {
    const response = await sdpApiRequest("/v1/issuance/asset-profiles", {
      method: "POST",
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const body = await response.text();
      const message =
        response.status === 403
          ? t("DashboardIssuance.errors.assetProfilesDisabled")
          : t("DashboardIssuance.errors.assetDraftCreateFailed", {
              status: response.status,
              error: parseErrorMessage(body),
            });
      return { state: "error", message, tokenId: null };
    }

    const json = (await response.json()) as {
      data?: { token?: { id?: string } };
    };
    const tokenId = json?.data?.token?.id ?? null;

    revalidatePath("/dashboard/issuance");
    return { state: "success", message: t("DashboardIssuance.errors.assetDraftCreated"), tokenId };
  } catch (error) {
    return {
      state: "error",
      message:
        error instanceof Error
          ? error.message
          : t("DashboardIssuance.errors.unableToCreateAssetDraft"),
      tokenId: null,
    };
  }
}
