export interface DeleteAssetDetails {
  asset_activities:             { deleted: string[]; errors: string[] };
  asset_movements:              { deleted: string[]; errors: string[] };
  asset_value_adjustments:      { deleted: string[]; errors: string[] };
  asset_depreciation_schedules: { deleted: string[]; errors: string[] };
  asset_maintenance:            { deleted: string[]; errors: string[] };
//   asset_repair:                 { deleted: string[]; errors: string[] };
}

export interface DeleteAssetResult {
  success: boolean;
  asset_name: string;
  details: DeleteAssetDetails;
}

export async function deleteAssetApi(assetName: string): Promise<DeleteAssetResult> {
  const response = await fetch(
    '/api/method/asset_lite.api.delete_asset.delete_asset',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ asset_name: assetName }),
    }
  );

  const data = await response.json();

  if (data.message?.success) {
    return data.message as DeleteAssetResult;
  }

  // Parse Frappe error format
  let errorMessage = 'Unknown server error';
  if (data._server_messages) {
    try {
      const parsed = JSON.parse(data._server_messages);
      const first = JSON.parse(parsed[0]);
      errorMessage = first.message || errorMessage;
    } catch {
      errorMessage = data._server_messages;
    }
  } else if (data.exc) {
    const lines = data.exc.split('\n').filter(Boolean);
    errorMessage = lines[lines.length - 1] || errorMessage;
  }

  throw new Error(errorMessage);
}